Interfaces in Java

Introduction to Object-Oriented Programming in Java

Sani Yusuf

Lead Software Engineering Content Developer

Limitations of inheritance

  • With inheritance, all members are inherited
  • You cannot selectively inherit members

  // Car class   
  class Car {
    // Battery capacity is only applicable
    // to electric cars
    public int batteryCapacity;

    void drive() {

    }  
  }


  // Toyata class
  class Toyota extends Car {  
    void drive(){

    }           
  }


// Man class public static class Main { public static void main(String[] args) { Toyota myToyota = new Toyota(); // All cars will inherit the "batteryCapacity" // even if they are not electric cars System.out.println( myToyota.batteryCapacity); // Not applicable } }
Introduction to Object-Oriented Programming in Java

Creating interfaces

  • Interfaces provide a way to selectively inherit properties and methods
  • Classes use interfaces using the implements keyword

  // ElectricCar Interface 
  interface ElectricCar {

  }





  // Tesla implementing the
  // ElectricCar interface
  class Tesla implements ElectricCar {

  }








Introduction to Object-Oriented Programming in Java

Adding properties to interfaces

  • Properties use UPPER_SNAKE_CASE by convention
  • Value must be set immediately and cannot be changed
  • Properties are public static final behind the scenes

  interface ElectricCar {
    // Implictly public static final
    // Cannot be changed
    int BATTERY_CAPACITY = 310;

  }




Introduction to Object-Oriented Programming in Java

Adding interface methods

  • Interfaces are typically used to house methods
  • The methods are abstract by default without code implementation
  • Interfaces can have concrete methods that have code implementation
  • All abstract methods must be implemented in the subclass
  interface ElectricCar {
    // Implictly public static final
    // Cannot be changed
    int BATTERY_CAPACITY = 310;


// This is an abstract method by default void charge();
// This is a concrete method void autoPark() { }
}
class Tesla implements ElectricCar { // Must be implemented public void charge() { } }
Introduction to Object-Oriented Programming in Java

Let's practice!

Introduction to Object-Oriented Programming in Java

Preparing Video For Download...