Interfaces and
packages
Interfaces
Interfaces add most of the functionality that
is required for many applications which would normally resort to using multiple
inheritance in a language such as C++.
Defining an Interface
An interface is defined much like a class. This is the
general from of an interface:
access
interface name {
return-type
method-name1(parameter-list);
return-type
method-name2(parameter-list);
type
final-varname1=value;
type
final-varname2=value;
//...
return-type
method-nameN(parameter-list);
type
final-varnameN=value;
}
Implementing Interfaces
class->class = extends
class->interface = implement
//Program to illustrate interfaces
File name: Area.java
interface
Area
{
final static double pi=3.14;
double compute(double x,double y);
}
File name: Rect1.java
class
Rect1 implements Area
{
public double compute(double x, double
y)
{
return(x*y);
}
}
File name: Circle.java
class
Circle implements Area
{
public double compute(double x, double
y)
{
return(pi*x*x);
}
}
File name: InterfaceTest.java
class
InterfaceTest
{
public static void main(String args[])
{
Rect1 r=new Rect1();
Circle c=new Circle();
Area area;
area=r;
System.out.println("Area
of the Rectangle = "+area.compute(10,20));
area=c;
System.out.println("Area of the Rectangle =
"+area.compute(10,0));
}
}
Output
Packages
collection class, object,method
To run package use this command
javac –d . classname.java
//A simple package
File name: Add.java
package
mypack;
public
class Add
{
public
void addition()
{
int
a=100;
int
b=200;
System.out.println("The
sum is: "+(a+b));
}
}
File name: Myclass.java
import
mypack.Add;
public
class Myclass
{
public
static void main(String args[])
{
Add
a=new Add();
a.addition();
}
}
Output
Example
//Package Program : Save the following
program in a directory called Math.
File Name : MathFun.java
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
float multiply(float a, float b)
{
return(a*b);
}
}
Hint:- The
following program to test the math package.Save the following program outside
of math folder.
//File Name:
PackTest.java
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 Interger:"+mf.sum(5,5));
System.out.println("Sum
of Two float Number:"+mf.sum(5.5f,5.3f));
}
}
Output
0 comments:
Post a Comment