Menu
Topics Index
...
`


Abstract Class And Methods >
Siva Nookala - 14 Apr 2016
We have seen the class hierarchies - Entertainments example in Java Class Inheritance and IceCreamPrices example in Inheritance Example Program To Remove Duplicate Code. The class hierarchies look similar except that there is minor difference between them. IceCream is a concrete super-class where as Entertainment is an abstract super-class. The difference is explained below.

In reality IceCream can exist, even with out FruitSaladWithIceCream, where as Entertainment can not exist on its own. It has to be either Movie, Drama or Circus or some other entertainment. Similarly Metal is an abstract class, since for we to show the Metal, we need to either show Gold or Iron or some thing else. If we had Mobile and MobileWithCamera, then Mobile would be a concrete class since it can exists on its own.
IceCream and Mobile are examples of concrete super-classes, where as Entertainment, Metal and Shape are examples of abstract super-classes.
In Java every class defined is by default concrete class, but if we want to implement abstract class, we need to use the abstract keyword before the class to mark a class as abstract class.
abstract class Shape
{
}

class Rectangle extends Shape
{
}
Here we have created an abstract class called Shape and a concrete class called Rectangle. Abstract class is prefixed with the keyword abstract, 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 shape1.
The other advantage of abstract classes is we can define abstract methods. They are explained in Abstract Method In Java.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.