We have seen the class hierarchies -
s example in Java Class Inheritance
example in Inheritance Example Program To Remove Duplicate Code
. The class hierarchies look similar except that there is minor difference between them.
is a concrete
super-class where as
is an abstract
super-class. The difference is explained below.
can exist, even with out
, where as
can not exist on its own. It has to be either
or some other entertainment. Similarly
is an abstract class, since for we to show the
, we need to either show
or some thing else. If we had
would be a concrete class since it can exists on its own.
are examples of concrete
super-classes, where as
are examples of abstract
In Java every class defined is by default concrete class, but if we want to implement abstract class, we need to use the
keyword before the class to mark a class as abstract class.
abstract class Shape
class Rectangle extends Shape
Here we have created an abstract
and a concrete
. Abstract class is prefixed with the keyword
, where as for concrete class we need not mention any keyword.
Shape shape1; // Can create a reference of abstract class
Shape shape2 = new Shape(); // WILL NOT WORK. Can not create an object of abstract class
Rectangle rect1 = new Rectangle(); // Can create reference and object of a concrete class
shape1 = rect1; // Can assign concrete sub-class reference to abstract super-class reference
- We can only create a reference for an abstract class, but can not create (or instantiate) an object of abstract class.
- We can create both reference and object for any concrete class.
- We can assign a concrete sub-class reference to abstract super-class reference. i.e.
rect1 can be assigned to
The other advantage of abstract classes is we can define abstract methods. They are explained in Abstract Method In Java