Java Extends vs Implements

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.

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.

One thought on “Java Extends vs Implements

Leave a Reply

Your email address will not be published. Required fields are marked *