Interface is similar to a class,
But methods in an
interface are all only declared, not implemented.
Interface has only the method signature unlike a class,
which also has method body as shown below.
Interface has only the method signature unlike a class,
which also has method body as shown below.
Class Interface
class Displayable { interface Displayable {
class Displayable { interface Displayable {
public void display(){ public void display();
System.out.println(" Display method");} }
System.out.println(" Display method");} }
}
That is, Interfaces can have only Abstract methods.
But, we also have Abstract classes,which can have only abstract methods.
(Abstract classes can have both abstract and functional
methods).
Then the question would be,
If we can have an abstract class with abstract methods, why we need Interface feature.
There are two reasons for it,
One:
Abstract class is a CLASS, where as Interface
is not a class.
The advantage is,
In Java, a Class can EXTEND only one class but a class can IMPLEMENT
more than one interface.
more than one interface.
Added to that, an Interface can EXTEND more than one Interface.
This feature of Interface enable Java to achieve multiple
inheritances,
which is not directly possible with class.
Second:
Abstract class being a class, it is used in classes which
are related.
Whereas, Interface, which is not a class, can be implemented by
classes
which are not related.
which are not related.
We will see the above advantages with examples.
Example Program with multiple inheritance:
A software company has employees under the categories as Programmers, Testers
and Programmer cum Testers.
Here,
We can have an Employee Class with personal details of employees
And, we can have subclasses for Programmers and Testers separately by
EXTENDING Employee class as below.
class programmers extends employee{
.....}
class testers extends employee{
.....}
Because,we can't extend more than one class - no subclass can have more than one super class.
That is,
class progCumTesters extends programmers, testers {
}
is wrong.
In these situations, Interface feature comes to our aid.
Because, we can't extend more than one class but we can implement interfaces.
We can have a class like,
class progCumTesters extends programmers implements testerinterface{
}
Here, we create an Interface for Tester details and implement it along
with Programmer class extension.
Program:
package multipleinheritance;
/* Employee base class */
class employee {
void eDetail(int eId,String eName){
System.out.println("Employee Id = "+eId);
System.out.println("Employee Name = "+eName);
}
}
/* Programmer subclass with employee detail inherited from Employee class */
class programmer extends employee {
void programmerDetail(){
System.out.println("Programmer Skill Details");
}
}
/* Tester subclass with employee detail inherited from Employee class */
class tester extends employee {
void testerDetail(){
System.out.println("Tester Skill Details");
}
}
/* Tester Interface to enable multiple inheritance */
interface testerInterface{
void testerDetail();
}
/* Programmer cum Tester class inherits Employee and Programmer detail
from programmer class and implemets Tester skills through Tester Interface */
class programmerCumTester extends programmer implements testerInterface{
public void testerDetail(){
System.out.println("Tester Skill Details");
};
}
public class MultipleInheritance {
public static void main(String[] args) {
System.out.println("EMPLOYEE as PROGRAMMER \n");
programmer p = new programmer(); // programmer object
p.eDetail (111, "Wilson");
p.programmerDetail();
System.out.println("\nEMPLOYEE as TESTER \n");
tester t = new tester(); // Tester Object
t.eDetail (111, "Wilson");
t.testerDetail();
System.out.println("\nEMPLOYEE as PROGRAMMER cum TESTER\n");
// programmer cum Tester Object
programmerCumTester pt = new programmerCumTester();
pt.eDetail(111,"Wilson");
pt.programmerDetail();
pt.testerDetail();
}
}
Output:
EMPLOYEE as PROGRAMMER
Employee Id = 111
Employee Name = Wilson
Programmer Skill Details
EMPLOYEE as TESTER
Employee Id = 111
Employee Name = Wilson
Tester Skill Details
EMPLOYEE as PROGRAMMER cum TESTER
Employee Id = 111
Employee Name = Wilson
Programmer Skill Details
Tester Skill Details
Example Program for using interface in unrelated classes.
An educational center wants arithmetic average (mean) of student marks.
A home buyer wants medium(median) cost house, that is middle value -
neither low and nor high cost wise.
neither low and nor high cost wise.
A Foot Wear company want to know which size would sell most (mode) in the market.
That is, which size has the highest frequency in a given set.
Naturally they belong to three different classes.
That is, which size has the highest frequency in a given set.
Naturally they belong to three different classes.
The above three situations are very different and they require three different type
of averages to be calculated.
But a common Interface can be implemented in the above different classes.
In this example, an Interface Average is created with method signatures for
Mean,Median and Mode averages.
Interface methods are implemented in the corresponding classes.
Mean method in Education Center.
Median method in Housing Company.
Mode methods in Foot Wear Company.
Program:
package interfaceexampe2;
import java.util.Arrays;
interface AverageInterface{
int mean();// Arithmetic average
int median();//Middle value in the list
int mode(); // Most common number present in the list
}
/*
AverageInterface used in an Education Center situation
An educational center would look for MEAN score of a student
*/
class Average implements AverageInterface{
public int mean(){
int marks[] = {55,65,75,85,95};
int i,sum =0;
for (i=0;i< marks.length;i++){
sum=sum +marks[i];
}
int meanAve = sum/marks.length;
for (i=0;i< marks.length;i++){
System.out.print(marks[i]+" ");
}
return meanAve;
}
/*
AverageInterface used in an Housing Company situation
An average home buyer would look for mid (MEDIAN) value home,
which is neither low nor high
*/
public int median(){
int i=0;
int housePrices[] = {20000,30000,40000,60000,70000,80000};
for (i=0;i< housePrices.length;i++){
System.out.print(housePrices[i]+" ");
}
int medianAve = housePrices[housePrices.length/2];
return medianAve;
}
/*
AverageInterface used in a Foot Wear Company situation
Company would look for most frequently(MODE) bought foot wear
size for production or marketing
*/
public int mode(){
int i=0;
int MostSaleable=0, cnt=0,mostFrequent=0;
int footwear[]={7,7,8,8,8,9,9,9,9,10,11,11};
for (i = 0; i < footwear.length; ++i) {
cnt = 0;
for (int j = 0; j < footwear.length; ++j) {
if (footwear[j] == footwear[i])
cnt =cnt +1;
}
if (cnt > mostFrequent) {
mostFrequent = cnt;
MostSaleable = footwear[i];
}
}
for (i=0;i< footwear.length;i++){
System.out.print(footwear[i]+" ");
}
return MostSaleable;
}
}
public class InterfaceExampe2 {
public static void main(String[] args) {
Average mmm = new Average();
System.out.println("Education Center - Student Marks");
System.out.println("\nMEAN (Arithmatic average of the Student) : "+ mmm.mean());
System.out.println("\nHousing Company - Cost of Houses");
System.out.println("\nMEDIAN(neither low,nor high value of a house) :"+ mmm.median());
System.out.println("\nShoe Company - Shoe size list");
System.out.println("\nMODE (Most Saleable Foot Wear Size) ="+ mmm.mode());
}
}
of averages to be calculated.
But a common Interface can be implemented in the above different classes.
In this example, an Interface Average is created with method signatures for
Mean,Median and Mode averages.
Interface methods are implemented in the corresponding classes.
Mean method in Education Center.
Median method in Housing Company.
Mode methods in Foot Wear Company.
Program:
package interfaceexampe2;
import java.util.Arrays;
interface AverageInterface{
int mean();// Arithmetic average
int median();//Middle value in the list
int mode(); // Most common number present in the list
}
/*
AverageInterface used in an Education Center situation
An educational center would look for MEAN score of a student
*/
class Average implements AverageInterface{
public int mean(){
int marks[] = {55,65,75,85,95};
int i,sum =0;
for (i=0;i< marks.length;i++){
sum=sum +marks[i];
}
int meanAve = sum/marks.length;
for (i=0;i< marks.length;i++){
System.out.print(marks[i]+" ");
}
return meanAve;
}
/*
AverageInterface used in an Housing Company situation
An average home buyer would look for mid (MEDIAN) value home,
which is neither low nor high
*/
public int median(){
int i=0;
int housePrices[] = {20000,30000,40000,60000,70000,80000};
for (i=0;i< housePrices.length;i++){
System.out.print(housePrices[i]+" ");
}
int medianAve = housePrices[housePrices.length/2];
return medianAve;
}
/*
AverageInterface used in a Foot Wear Company situation
Company would look for most frequently(MODE) bought foot wear
size for production or marketing
*/
public int mode(){
int i=0;
int MostSaleable=0, cnt=0,mostFrequent=0;
int footwear[]={7,7,8,8,8,9,9,9,9,10,11,11};
for (i = 0; i < footwear.length; ++i) {
cnt = 0;
for (int j = 0; j < footwear.length; ++j) {
if (footwear[j] == footwear[i])
cnt =cnt +1;
}
if (cnt > mostFrequent) {
mostFrequent = cnt;
MostSaleable = footwear[i];
}
}
for (i=0;i< footwear.length;i++){
System.out.print(footwear[i]+" ");
}
return MostSaleable;
}
}
public class InterfaceExampe2 {
public static void main(String[] args) {
Average mmm = new Average();
System.out.println("Education Center - Student Marks");
System.out.println("\nMEAN (Arithmatic average of the Student) : "+ mmm.mean());
System.out.println("\nHousing Company - Cost of Houses");
System.out.println("\nMEDIAN(neither low,nor high value of a house) :"+ mmm.median());
System.out.println("\nShoe Company - Shoe size list");
System.out.println("\nMODE (Most Saleable Foot Wear Size) ="+ mmm.mode());
}
}
Output:
run:
Education Center - Student Marks
55 65 75 85 95
MEAN (Arithmatic average of the Student) : 75
Housing Company - Cost of Houses
20000 30000 40000 60000 70000 80000
MEDIAN(neither low,nor high value of a house) :60000
Foot Wear Company - Foot Wear size set
7 7 8 8 8 9 9 9 9 10 11 11
MODE (Most Saleable Foot Wear Size) =9
Some important points :
- All methods in an Interface are abstract
- All variables are public,static and final( no need to specify)
- Methods are to be overridden,so they can't be private, protected or final.
Some important points :
- All methods in an Interface are abstract
- All variables are public,static and final( no need to specify)
- Methods are to be overridden,so they can't be private, protected or final.