There are two types inheritance: Class inheritance which has been allready described and Interface inheritance (subtyping).


An interface looks like a concrete class with one important difference: attributes and methods are only declared but not defined. An object can not be created from type of an interface!

1 public interface IAccount {             // Definition of an interface
2     int INITIAL_BALANCE = 50;           // attributes are public, static and final by default
3 
4     int transaction(double amount);     // no definitions of methods only deklarations
5     double getBalance();                // all methods are public by default
6 }

Example of an interface in Java


Subsequently interfaces specify only what the class is doing, not how it is doing it. The implementing class of that interface has to define every method wich is declared by the interface and specifiy how to do it:

 1 public class Account implements IAccount{       // Interface is implemented by class
 2     protected double balance;
 3 
 4     public Account() {
 5         balance = INITIAL_BALANCE;
 6     }
 7 
 8     public int transaction(double amount) {     // Methods declared by implemented interfaces
 9         balance += amount;                      // now have to be defined
10         return 0;
11     }
12     public double getBalance() {
13         return balance;
14     }
15 }

Example of an class which implements this interface in Java


An interface defines what the behavior a an object will have, but it will not actually specify the behavior. It is a contract, that will guarantee, that a certain class can do something.

UML class diagram: Implementation of an interfaceUML class diagram: Implementation of an interface



Summary

  • An object of an interface cannot be created,
  • but an interface describes what the implementing class should can do, without specifying how to do it.
  • Subsequently a class that implements interface must implements all the methods in interface.
  • A class can implement more than one interface. That means it can be used used to achieve multiple inheritance.
  • An interface can extends one or more another interfaces.
  • All the methods are public and abstract, and all the attributes are public, static, and final by default.


New features added in interfaces in JDK 9
From Java 9 onwards, interfaces can contain following also

  1. Static methods
  2. Private methods
  3. Private Static methods
which are not considered at this point.


Last modified: Tuesday, 21 May 2019, 9:00 PM