Reputation: 492
If you have an abstract superclass named Car, and you have various subclasses of it, and abstract methods with no implementation, why bother with having an abstract class reference variable. i.e
Car myCar=new Honda();
In the Car class there are only abstract methods with no implementation so it would be useless to have right?
Upvotes: 1
Views: 772
Reputation: 2824
Not really. Car is an abstraction above Honda. So that in the future, you can swap out Honda without worrying about massively modifying the code. In my case, I switched from a Honda Civic to a Subaru Outback as my family grew. Guess what, I don't need to re-learn driving, because the "driving API" remains the same and I already know how to drive a Car.
Upvotes: 0
Reputation: 234807
It's not useless at all. It allows you to write code that relies on the object being a Car
without knowing anything about the specific type of Car
.
public abstract class Car {
public abstract void tootHorn();
public abstract void swerve();
. . .
}
public class Driver {
private Car car;
public Driver(Car car) {
this.car = car;
}
public void dealWithDanger() {
car.tootHorn();
car.swerve();
}
. . .
}
In the above code as posted, Car
could just as easily have been an interface
. By making it a class, though, it is possible to implement some methods directly in the Car
class that depends on the (as-yet unspecified) behavior of abstract methods that are specified by subclasses.
The key point of abstract classes is that you never have an instance of the abstract class itself; code can only create instances of some concrete subclass. Nevertheless, lots of application logic can be written to be independent of the specific class of an object.
Upvotes: 5
Reputation: 1847
take a look at this: http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html i think that would answer your question
Upvotes: 0
Reputation: 19288
The abstract part prevents you from creating a car object like this:
Car car = new Car();
It makes no sense to create just a car.
Upvotes: 0