In: Computer Science
What are some of the advantages of creating abstract classes? Are there any potential downsides to using parent classes and subclasses?
Answer) Advantages of abstract classes
1) The abstract class provides Abstraction. Abstraction is a key feature of object-oriented programming languages which provides the generalised view of the system which can then be overridden by the child classes according to the requirement.
2) To create abstract methods which are overridden by child classes.
For example, if we create an abstract class Car. Then the car has various attributes such as colour, engine, type and so on. The class consist of the abstract method which has to be overridden. Now we can create a child class BMW which will extend abstract Car class and then override the methods according to colour, engine or type. Similarly, we can create an extend another class Toyota and override accordingly. See the example code below:
absract class Car
{
abstract void car_color() ;
abstract void car_type() ;
abstract void car_engine() ;
}
// child class BMW extends and then overrides accordingly.
class BMW extends Car
{
abstract void car_color()
{
int color =1;
}
abstract void car_type()
{
type = awesome ;
}
abstract void car_engine()
{
engine = robust ;
}
void special_features ()
{
Freebies = style +comfort - money ;
}
}
// child class Toyota extends and then overrides accordingly.
class Toyota
{
abstract car_color()
{
int color =3;
}
abstract car_type()
{
type = good ;
}
abstract car_engine()
{
type = good ;
}
}
3) Code reusability: The generalisation leads to the code reusability as the same abstract class can be extended and then overridden instead of writing child class from scratch. All methods of Car is added also importantly, BMW and Toyota have its own features and hence leads to code reusability.
Disadvantages:
The main disadvantage of the abstract class is that we can create an object of the abstract class.
Another disadvantage is that parent and subclass gets tightly coupled. which means that they cannot be used independently from each other.