Object Oriented

Interface

Java

 

Interface

Java 8
interface myInterface {
  
  // ...
  
}

Interface is a tool to achieve better abstraction.

Interface specifies a list of methods that Classes should implement.

Interface is a blueprint for Classes, just like Class are blueprints for Objects.

 

Interface Method

Java 8
// JobInterface.java file
interface JobInterface {
  public void work();
}

// Teacher.java file
class Teacher implements JobInterface {
  public void work() {
    System.out.println("I'm teaching");
  }
}

In this example, any Class that is not abstract and implements the JobInterface should implement the work method, otherwise compiling fails.

A Class can implement one or more Interfaces separated by ,.

 

Interface Constant

Java 8
// JobInterface.java file
interface JobInterface {
  final double MINIMUM_WAGE = 7.25;
  
  public void work();
}

// Teacher.java file
class Teacher implements JobInterface {
  public void work() {
    System.out.println("Teach for not less than " + this.MINIMUM_WAGE);
  }
}

Interface may contain constants or statics.

Teacher teacher1 = new Teacher();
teacher1.work();  // Teach for not less than 7.25

There are couple of ways to access Interface Constants and Statics (based on the context):

  • JobInterface.MINIMUM_WAGE
  • Teacher.MINIMUM_WAGE
  • this.MINIMUM_WAGE
  • teacher1.MINIMUM_WAGE
 

Abstract Class

Java 8
abstract class Teacher {
  public String name;
  
  public void greet() {
    System.out.println("Hello Students!"); 
  }
  
  abstract void work();
}

class PhysicsTeacher extends Teacher {
  public void work() {
    System.out.println("I'm teaching physics!");
  }
}

Abstract Class is specified with abstract.

Abstract Class can have abstract methods.

Abstract Method is a method without an implementation.

Abstract Classes cannot be instantiated, because they are incomplete.

In Java you can only extend from one parent Class.

PhysicsTeacher teacher1 = new PhysicsTeacher();
teacher1.greet();   // Hello Students!
teacher1.work();    // I'm teaching physics!