Skip to content

Abstract class VS Interface in a nutshell

ck-109 edited this page Mar 12, 2021 · 1 revision

Abstract Class

  • Cannot have multiple inheritance. Aka sub class can only extends from one parent. Eg, class Child extends Parent { … }
  • The Child class must contain all the abstract methods declared. All the overridden methods in its Child class must be public. Can have method definition. Eg, toString()
  • Can have method definition. Eg, toString()
  • Can have properties / attributes
  • Members can be private/ protected/ public etc.
  • abstract keyword is needed in front of the class and methods. Eg, abstract class Hotel { abstract int roomNum { … } }
  • Cannot have multiple inheritance. Aka sub class can only extends from one parent. Eg, class Child extends Parent { … }

Interface

  • Allows for multiple inheritance. Can inherit ‘behaviors’ from multiple interfaces. Eg, class Child implements A, B, C { … }
  • All the overridden methods in its Child class must be public.
  • Cannot have method definition. Eg, toString()
  • Cannot have properties / attributes
  • Members are all public by default.
  • There is no need for an abstract keyword after Java 8.
  • Allows for multiple inheritance. Can inherit ‘behaviors’ from multiple interfaces. Eg, class Child implements A, B, C { … }

When to use which?

Scenario 1: You have multiple classes with the exact same method.

  • An abstract class will be more appropriate.
  • It removes code repetitions.

Scenario 2: You have multiple classes with same method name but different implementation of code.

  • An interface would be more appropriate.
  • Override the method from interface.

Scenario 3: If you want to inherit multiple ‘behaviors’ from multiple parents.

  • An interface would be more appropriate.
  • Allows multiple inheritance of ‘behavior’.

All in all,

  • Use abstract class if you have common methods between multiple classes.
  • Use interface if you want more flexibility.