What is Abstract Class and what is use
Answer:
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject { // declare fields // declare nonabstract methods abstract void draw(); }
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.
Uses:
- The main purpose of an abstract class is if you have common code to use in sub classes but the abstract class should not have instances of its own.
- 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).
- When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
- The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
- 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”.