Abstraction & Interfaces

Abstraction & Interfaces

Abstraction

  1. 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

  1. 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)
}
  1. 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

  1. By default interface class is abstract so there is no need to mention it
  2. The methods implemented inside the class are public and abstract
  3. 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
  4. We cannot use the implement keyword for one interface to another interface
  5. Instead we can use the extend keyword for interfaces
  6. The difference between classical inheritance and the inheritance due to an interface is interface inheritance we can have diamond and multiple interfaces
  7. Interface Methods cannot be final, strictfp, or native as the final keyword does not participate in inheritance
  8. Interface methods can have a body if a static or default modifier is used against the method
  9. We cannot create objects of interface class
  10. We can create the reference of the abstract class
  11. All method rules like parameter list are applicable to the class which implements the interface
  12. As we can create the reference variable of abstract class it will participate in inheritance