abstract-classabstract-methods

When and Why to use abstract classes/methods?


I have some basic questions about abstract classes/methods. I know the basic use of abstract classes is to create templates for future classes. But are there any more uses for them? When should you prefer them over interfaces and when not? Also, when are abstract methods useful?


Solution

  • I know the basic use of abstract classes is to create templates for future classes. But are there any more uses of them?

    Not only can you define a template for children, but Abstract Classes offer the added benefit of letting you define the functionality that your child classes can utilize later.

    You could not provide a default method implementation in an Interface prior to Java 8.

    When should you prefer them over interfaces and when not?

    Abstract Classes are a good fit if you want to provide implementation details to your children but don't want to allow an instance of your class to be directly instantiated (which allows you to partially define a class).

    If you want to simply define a contract for Objects to follow, then use an Interface.

    Also when are abstract methods useful?

    Abstract methods are useful in the same way that defining methods in an interface is useful. It's a way for the designer of the Abstract class to say "any child of mine MUST implement this method".