A programmer uses an abstract
class when there are some common features shared by all the objects. A
programmer writes an interface when all the features have different
implementations for different objects. Interfaces are written when the
programmer wants to leave the implementation to third party vendors. An
interface is a specification of method prototypes. All the methods in an
interface are abstract methods.
· An
interface is a specification of method prototypes.
· An
interface contains zero or more abstract methods.
· All
the methods of interface are public, abstract by default.
· An
interface may contain variables which are by default public static final.
· All
the methods of the interface should be implemented in its implementation
classes.
· If any one of the method is not
implemented, then that implementation class should be declared as abstract.
· We
cannot create an object to an interface.
· We
can create a reference variable to an interface.
· An
interface cannot implement another interface.
· An
interface can extend another interface.
· A
class can implement multiple interfaces.
Program 1: Write an example program for interface interface Shape
{
void area ();
void volume ();
double pi = 3.14;
}
class Circle implements Shape
{ double r;
Circle (double radius)
{ r
= radius;
}
public void area ()
{ System.out.println
("Area of a circle is : " +
pi*r*r );
}
public void volume ()
{ System.out.println
("Volume of a circle is : " +
2*pi*r);
}
}
class Rectangle implements Shape
{ double l,b;
Rectangle (double length, double
breadth)
{
l = length; b
= breadth;
}
public void area ()
{ System.out.println
("Area of a Rectangle is : " +
l*b );
}
public void volume ()
{ System.out.println
("Volume of a Rectangle is : "
+ 2*(l+b));
}
}
class InterfaceDemo
{ public static void main (String
args[])
{
Circle
ob1 = new Circle (10.2);
ob1.area
();
ob1.volume
();
Rectangle
ob2 = new Rectangle (12.6, 23.55);
ob2.area
();
ob2.volume
();
}
}
Output:
Types of inheritance:
· Single Inheritance:
Producing subclass from a single super class is called single inheritance
· Multiple Inheritance: Producing
subclass from more than one super class is called Multiple
Java does not support multiple inheritance. But multiple inheritance can be achieved by using interfaces.
Java does not support multiple inheritance. But multiple inheritance can be achieved by using interfaces.
Program 2: Write
a program to illustrate how to achieve multiple inheritance using multiple
interfaces. //interface Demo
interface Father
{ double
PROPERTY = 10000;
double HEIGHT = 5.6;
}
interface Mother
{ double
PROPERTY = 30000;
double HEIGHT = 5.4;
}
class MyClass implements Father, Mother
{ void show()
{ System.out.println("Total property is
:" +(Father.PROPERTY+Mother.PROPERTY));
System.out.println ("Average height is :" + (Father.HEIGHT +
Mother.HEIGHT)/2 );
}
}
class InterfaceDemo
{ public
static void main(String args[])
{
MyClass ob1 = new MyClass(); ob1.show();
}
}
Output: