Reputation: 811
I know about the conceptual use behind creating an abstract class, i.e. defining a common interface for its subclasses where some of the implementation is left to the individual subclasses.
Am I correct in my assumption that there is technically no necessary need for abstract classes, since you can overwrite a superclass method anyway? Were abstract classes just created to make the intention of the classes clearer to the developer?
Example of what I mean:
// Using an abstract class
abstract class Car
{
int fuel;
int getFuel()
{
return this.fuel;
}
abstract String getColor();
}
class RedCar extends Car
{
String getColor()
{
return "red";
}
}
// Without an abstract class
class Car
{
int fuel;
int getFuel()
{
return this.fuel;
}
String getColor()
{
return "defaultColor";
}
class RedCar extends Car
{
String getColor()
{
return "red";
}
}
Upvotes: 0
Views: 130
Reputation: 271625
Were abstract classes just created to make the intention of the classes clearer to the developer?
That's right, but it also prevents developers from doing "silly" things.
For example, you cannot create instances of abstract classes. In the context of your code, it does not make sense to create a "general" Car
. You can only create a BlueCar
or a RedCar
or some other subclass. While instances of an anonymous subclass may seem like instances of an abstract classes, they are in the end constructed from subclasses. If you made the Car
class abstracted, however, developers will not accidentally create an instance of Car
, because the compiler would complain.
Abstract classes also forces developers to implement the abstract methods. With your non-abstract Car
class, I can inherit it and forget that I need to override getColor
. Now some other parts of the code might call getColor
and gets a nonsensical result "defaultcolor". What the heck is a default color? Making the method abstract forces the subclasses to think about implementing the required methods.
Upvotes: 5
Reputation: 1085
Most people I know avoid abstract classes. From an application programmers point of view, my opinion is that abstract classes should be avoided. Using interfaces are so much more flexible not forcing your work to adhere to a class hierarchy.
a bit formally: an abstract class is strict inheritance, while interfaces are composition.
An example where abstract classes are useful is when making class libraries. The hierarchy that abstract classes enforces, can make the library more easily understandable for application programmers. However, I do believe this comes at the cost of longer development times of the library.
Upvotes: -1