- Interface are useful when a class unrelated class have similar set of methods.
- Syntax:
// abstract methods
}
- All method in interface are public and abstract
- All variable are public static final variable
- Interfaces are like classes but do not have instance variables and all the methods are abstract.
- Interface can be used by "implements" keyword
- Once the interface has be defined any number of interface can be used with the class
Thus interfaces support Multiple inheritance
Lets see how interface over come the problem of ambiguity?
Take two interfaces
Interface DisplayName have abstract method note here we do not write abstract keyword in declaration of the method as Method inside interface are by default abstract
public interface DisplayName{
public void display();
}
Interface DisplayName have abstract method
public interface DisplayId{
public void display();
}
Class Customer implements DispayName,DisplayId{
// override the method display();
public void display(){
System.out.println("Overriden Method");
}
public static void main(String...s){
Customer c = new Customer();
c.display();
}
}
Here we override display method which is present in both the interface so how compiler would know which method to override.It simple both the interface are having these method definition but not the implementation and whenever case like this arises java will choose any one of the method and override it because definition is not provided so no ambiguity caused. and works fine Hence we can say that Interface support Multiple inheritance.
- If a class implements interface it must give all the methods defined inside the Interface a definition or it should be declared abstract
- A class can extend any class and at the same time can implement any number of interfaces
<Class> extends <class> implements<interface>,<interface><interface><interface>{
}
- An interface can extend other interface by "extends" keyword
Difference between Abstract class and Interface
Self study
Can you answer there questions?
1.interface Example{
1.interface Example{
int num=90;
public abstract void disp();
public abstract void display();
}
class Example1
implements Example{
public void display(){
System.out.println("display
in Example1");
}
public void disp(){
int num=900;
System.out.println(num);
}
}
class Demo{
public static void main(String args[]){
Example1 obj=new
Example1();
obj.display();
obj.disp();
}
}
2. interface Example{
public abstract void display();
}
interface Example1{
public void disp();
}
abstract class
Example2 implements Example,Example1{
}
class Example3
extends Example2{
public void display(){
System.out.println("display
in Example3");
}
public void disp(){
System.out.println("disp in
Example3");
}
}
class Demo{
public static void main(String args[]){
Example3 obj=new
Example3();
obj.display();
obj.disp();
}
}
You can answer these question by comment and i will share the correct answer later.
Thanks for reading by blogs

0 comments :
Post a Comment