Table of contents
Abstraction
- It is basically hiding the implementation and can be achieved in 2 ways
a. Abstract class ( 0 -100 %) of abstraction b. Interfaces (100%) of abstraction
Interfaces
- An interface is a completely "abstract class" that is used to group related methods with empty bodies:
example :
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
- To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the "implement" class:
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Pig "implements" the Animal interface
class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Rules For Writing An Interface
- By default interface class is abstract so there is no need to mention it
- The methods implemented inside the class are public and abstract
- We can give the body of the abstract method by using the default keyword, here the default keyword does acts as an access modifier instead it will act like a keyword
- We cannot use the implement keyword for one interface to another interface
- Instead we can use the extend keyword for interfaces
- The difference between classical inheritance and the inheritance due to an interface is interface inheritance we can have diamond and multiple interfaces
- Interface Methods cannot be final, strictfp, or native as the final keyword does not participate in inheritance
- Interface methods can have a body if a static or default modifier is used against the method
- We cannot create objects of interface class
- We can create the reference of the abstract class
- All method rules like parameter list are applicable to the class which implements the interface
- As we can create the reference variable of abstract class it will participate in inheritance