-
Notifications
You must be signed in to change notification settings - Fork 2
Abstract class VS Interface in a nutshell
ck-109 edited this page Mar 12, 2021
·
1 revision
- 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 { … }
- 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 { … }
- An abstract class will be more appropriate.
- It removes code repetitions.
- An interface would be more appropriate.
- Override the method from interface.
- An interface would be more appropriate.
- Allows multiple inheritance of ‘behavior’.
- Use abstract class if you have common methods between multiple classes.
- Use interface if you want more flexibility.