To be simple, an abstract class means you cannot create a new instance of this class.
However, it's still possible to declare an object as a Ship
(compile-time type vs runtime type) to use the polymorphism, allows you to do some funny stuff like an array of Ship
which contains both Submarine
and Destroyer
(and many more).
Ship[] army = new Ship[2];
army[0] = new Submarine("0");
army[1] = new Destroyer("1");
for( Ship s : army ) {
s.fire();
}
In this sample, we can invoke fire()
on the two object because fire()
is a method of Ship
. As the ship's attack depends on the ship's type (a submarine will not fire like a destroyer), you set the fire()
method of Ship
abstract and implements it in Submarine
and Destroyer
.
These tricks are essential in OOP, and allows you to implement powerful design patterns. If you're a beginner, looks at the strategy pattern and the template method pattern, they changed my vision of OOP few years ago ;)
Hope this little sample helps you :)