Java Extends vs Implements


Extends vs Implements: Once you know the basic structure of a Java class, know inheritance with concrete classes and abstract classes, know to inherit interfaces, it is the time for both extends and implements where you inherit classes and interfaces to one class.

For example, you have two classes (one may be abstract and the other non-abstract) and two interfaces to inherit and how to do the job let us see (remember, Java does not support multiple inheritance with classes).

Rules of using Extends vs Implements

  1. After extends keyword there can be only one class of either concrete class or abstract class
  2. After implements keyword there must interfaces only of any number.

For classes we use extends keyword and for interfaces we use implements keyword. In the following program, Test1 is concrete class, Test2 is abstract class, Hello1 and Hello2 are interfaces. See the code and learn the way of adapting inheritance.

interface Hello1		               // 1st interface
{
  public abstract void display1();
}
interface Hello2		               // 2nd interface
{
  public abstract void display2();
}

class Test1		                       // concrete (non-abstract) class
{
  public void calculate()
  {
    System.out.println("Concrete class Test1 method calculate() executed");
  }
}

abstract class Test2 extends Test1	       // abstract class extending Test1
{
  public abstract void show();
}

public class Demo extends Test2 implements Hello1, Hello2
{
  public void display1()
  {
    System.out.println("Interface Hello1 method display1() executed");
  }
  public void display2()
  {
    System.out.println("Interface Hello2 method display2() executed");
  }
  public void show()
  {
    System.out.println("Abstract class Test2 method show() executed");
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
    d1.display1();      
    d1.display2();
    d1.calculate();
    d1.show();
  }
}

Extends vs Implements

abstract class Test2 extends Test1

When multiple classes exist to inherit, as Java does not support multiple inheritance, use multilevel inheritance where you extend one class to the other in a ladder (explained in Java Extend Multiple Classes). Finally any one class in the ladder, you like, inherit to any class you require with extends keyword. The same is done in the above code. As we cannot extend both Test1 and Test2 to Demo, we made Test2 extends Test1 and this Test2 is extended to Demo class as Demo wants to inherit.

public class Demo extends Test2 implements Hello1, Hello2

Both interfaces Hello1 and Hello2 are implemented as Java supports multiple inheritance with interfaces.

To get command over inheritance, practice with different combinations of abstract classes, concrete classes and interfaces.

1 thought on “Java Extends vs Implements”

Leave a Comment

Your email address will not be published.