Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to implement an interface and when to extend a superclass?

I've been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever really compares the two side by side and explains when and why you would want to use one or the other. I have not found a lot of times when implementing an interface would be a better system than extending a superclass.

So when do you implement an interface and when do you extend a superclass?

like image 636
Agrajag9 Avatar asked Jul 22 '10 17:07

Agrajag9


People also ask

When to use interface vs extend?

A subclass or more than one subclass can extend only one parent class at the same time. A class can implement one or more than one interface at the same time. An interface can extend any number of interfaces. An interface can never implement any other interface.

Can you implement an interface and extend a class?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Should implements or extends first?

The extends always precedes the implements keyword in any Java class declaration. When the Java compiler compiles a class into bytecode, it must first look to a parent class because the underlying implementation of classes is to point to the bytecode of the parent class - which holds the relevant methods and fields.

Can an interface extends a class just like a class implements interface?

An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. An interface extends another interface like a class implements an interface in interface inheritance.


1 Answers

Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.

Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).

An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.

like image 57
BalusC Avatar answered Sep 20 '22 04:09

BalusC