Interfaces
I have explained you in a past article about Inheritance. But here I'm going to talk about Multiple Inheritance. Multiple Inheritance is extending one class to many classes. But its not allowed in Java. As a solution OOP gave us Interfaces. Interface is like a class (That means it has all the features that a class have) But Interface is not a class. We can use Interfaces in /java if we need to use multiple inheritance. Java has no limit for multiple inheritance using Interfaces. but when we are inheriting Interfaces we use the keyword implements not extends
Creating an Interface
Ex :- 1) Interface Saman {
}
- We create an interface in the way we are creating a class.
Inheriting an Interface to a Class
Ex :- 2) class A {
}
Interface B {
}
Interface B implements A {
}
Ex :- 3) class Cat {
}
class Dog {
}
Interface Eat {
}
class Cat extends Dog implements Eat {
}
class F
class A
class B
Interface C
Interface D
Interface E
class F extends A,B implements C,D,E{
}
Creating Objects
F f = new F (); (Correct)
C c = new F (); (Correct)
Orange color marked "C" is the Reference.
Red color marked "F" is the Object.
Interfaces can store sub classes acting as a super class
D d = new E ();
C c = new C ();
Orange color marked D & C are references. (Correct)
Red color marked E & C are invalid Objects. (Wrong)
When we are creating objects in interfaces we can use references as super references.
But we can't use the name of interface to create objects.
Refer to this code sample given below,
class A {
A () { // constructor
//We will enter the work that constructor needs to do when its started, here.
}
public static void main (String[]args){
A a = new A ();
}
}
- We cannot create a constructor in an Interface because we can't create objects
Interface - Methods - (Abstract Methods)
(Only Abstract methods can be stored in an Interface & We need to modify the abstract methods with the public modifier except the abstract methods in the interface)
Interface A {
public abstract void B ();
}
This is the way that we need to keep a meaningless method in an interface.
Public - Accessed for everyone.
Static - Accessed everywhere.
Final - End
If we are creating variables in an interface they should be public static final.
Example :- public static final int a; (We can assign a value to this "a" )
public static final int b = 5; Final Value (No one can change.)
public static final String c = "abcd"; Final Value (No one can change.)
public static final variables are called constant variables
We use extends keyword to inherit an interface to another interface.
Class to Class (extends)
Class to Interface (implements)
Interface to Interface (extends)


Comments
Post a Comment