Interface in JAVA:
- It is also type definition block.
Syntax : Interface InterfaceName{
Variables
Methods
}
- Interface is 100% abstract.
- In Interface by default all variables are static and final.
- In Interface variables should be declared and initialize in same time.
- Here, all methods are by default abstract and public.
- As Interface contains only abstract class, object creation is impossible.
- While implementing interface methods in sub classes, in subclass access specifier for a method should be public.
- Multiple Inheritances can be achieved in java by using Interface concept.
- If we create an interface then we create an instruction for the implementation.
- You expect that unrelated classes would implement your interface.
- You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
- You want to take advantage of multiple inheritance of type.
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
public interface InterfaceSample {
void test1();
void test2();
}
abstract class B implements InterfaceSample{
public void test1(){
System.out.println("test1 in class B
");
}
public void test2(){
System.out.println("test2 in class B
");
}
}
class c extends B{
public void test2(){
System.out.println("test2 in class C");
}
}
class Run2{
public static void main(String [] args){
System.out.println("Program start");
c c1 = new c();
c1.test1();
c1.test2();
System.out.println("Program ends");
}
}
O/P:
Program start
test1() in class B
test2() in class C
Program ends
Multiple Inheritances is possible using Interface:
Sample Program:
public interface InterfaceSample {
void test1();
}
class B {
public void test2(){
System.out.println("test2 in class B
");
}
}
class c extends B implements InterfaceSample{
public void test1(){
System.out.println("test1 in class C");
}
}
class Run2{
public static void main(String [] args){
System.out.println("Program start");
c c1 = new c();
c1.test1();
c1.test2();
System.out.println("Program ends");
}
}
o/p: test1() in class B
test2()
in class C