Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use abstract class or interface? [closed]

Why are abstract or interface classes created, or when should we use abstract or interface classes?

like image 659
JavaResp Avatar asked Aug 03 '09 09:08

JavaResp


People also ask

In which situations interfaces better than abstract classes?

An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.

What is advantage of using interfaces over abstract classes?

The main advantages of interface over abstract class is to overcome the occurrence of diamond problem and achieve multiple inheritance. In java there is no solution provided for diamond problem using classes. For this reason multiple inheritance is block using classes in java.

When should we go for abstract class?

If we are using inheritance then the abstract class can be used because it provides a common base class for derived classes. If we want to declare non-public members then abstract class is a better choice than interface because in an interface all methods must be public.

Which is faster abstract class or interface?

The fourth difference between abstract class and interface in Java is that abstract classes are slightly faster than the interface because the interface involves a search before calling any overridden method in Java.


1 Answers

Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.

If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.

--EDIT - forgot to mention, Earwicker reminded me

Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.

like image 168
Samuel Carrijo Avatar answered Oct 03 '22 20:10

Samuel Carrijo