Unit V Interface and Package
Unit V Interface and Package
interface InterfaceName
variable declaration;
method declaration;
Interface is similar to class which is collection of public static final variables (constants) and abstract
methods.
interface item
void display();
It is implicitly abstract. So we no need to use the abstract keyword when declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
All the data members of interface are implicitly public static final.
Extending interfaces
Body of name 2
For example, we can put all constants in one interface and all methods in other interface.
Interface ItemConstants
void display();
Interface ItemConstants
{
interface ItemMethods
void display();
………………………………
………………………………
Implementing Interfaces
Interfaces are used as “superclass” whose properties are inherited by classes. It is therefore necessary to
create a class that inherits the given interface.
body of className.
Body of classname;
{ {
{ System.out.println("Marks2="+m2);
rollno=n; }
} }
{ {
} void putscore();
} }
class test extends student class results extends test implements sports
{ {
{ {
System.out.println("sport score="+score);
m1=mark1; }
} {
total=m1+m2+score; r.getmarks(77.5,88.8);
putnumber(); r.display();
putmarks(); }
putscore(); }
} Rollno=103
} Marks obtained:
{ Mark2=88.5
r.getnumber(103); Total=171.0
2. There properties can be reused commonly in a 2. There properties commonly usable in any
Which may contain either variable or constants. 5. Which should contains only constants.
6. The default access specifier of abstract class 6. There default access specifier of interface
8. Inside abstract class we can take constructor. 8. Inside interface we can not take any constructor.
Example of Interface
// Interface.java
interface PI{
static final float pi = 3.1416f;
}
interface Area extends PI{
public float getArea(float x, float y);
}
interface Shape extends Area{
public void display(float x, float y);
}
class Rectangle implements Shape{
public float getArea(float x, float y) {
return x * y;
}
public void display(float x, float y){}
}
class Circle implements Shape{
public float getArea(float x, float y) {
return pi * x * x;
}
public void display(float x, float y){}
}
class Interface {
public static void main(String[] args) {
Rectangle r = new Rectangle();
Circle c = new Circle();
Shape s;
s = r;
System.out.println(s.getArea(2,3));
s = c;
System.out.println(s.getArea(4,0));
}
}