Unit-10 Interfaces and Packages

Implementing Interfaces in Java…

Example : Program to illustrate interfaces

 import java.io.*;
interface Area
{
	final static double pi=3.14;
	double compute(double x,double y);
}
class Rect implements Area
{
	public double compute(double x,double y)
	{
	return(x*y);
	}
}
class Circle implements Area
{
	public double compute(double x,double y)
	{
		return(pi*x*x);
	}
}
class InterfaceTest
{
	public static void main(String args[])
	{
	Rect r=new Rect();
	Circle c=new Circle();
	Area area;
	area=r;
	System.out.println("Area of Rectangle="+area.compute(10,20));
	area=c;
	System.out.println("Area of Circle="+area.compute(10,0));
	}
}

Output : InterfaceTest

Classpath in Java…

Example : A simple package

import java.io.*;
class Balance
{
String name;
double bal;
Balance(String n,double b)
{
name=n;
bal=b;
}
void show()
{
if(bal<0)
System.out.println("-->");
System.out.println(name+":$"+bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[]=new Balance[3];
current[0]=new Balance("K.J.Fielding",123.123);
current[1]=new Balance("Will Tell",145.33);
current[2]=new Balance("Tom Jackson",-32.3);
for(int i=0;i<3;i++)current[i].show();
}
}
Output : AccountBalance

Importing Packages in Java…

Package program : Save the following program in a directory called Math.

FileName : MathFun.java

//import java.io.*;
package Math;
public class MathFun
{
	public int fact(int num)
	{
		if(num == 1)
		return 1;
	else
		return(num*fact(--num));
	}
	public int square(int num)
	{
		return(num*num);
	}
	public int cube(int num)
	{
		return(num*num*num);
	}
	public int sum(int a,int b)
	{
		return(a+b);
	}
	public float sum(float a,float b)
	{
		return(a+b);
	}
	public int multiply(int a,int b)
	{
		return(a*b);
	}
	public float multiply(float a,float b)
	{
		return(a*b);
	}
}

Hint : Save the following program outside of Math folder.

import Math.MathFun;
class PackTest
{
	public static void main(String args[])
	{
		MathFun mf=new MathFun();
		System.out.println("Factorial:"+mf.fact(5));
		System.out.println("Square:"+mf.square(5));
		System.out.println("Cube:"+mf.cube(5));
		System.out.println("Sum of Two Integers:"+mf.sum(5,5));
		System.out.println("Sum of Two Float Numbers:"+mf.sum(5.5f,5.3f));
	}
}
Output : PackTest