Sunday, July 22, 2012

Abstract Classes: Runtime Polymorphism



Before reading this post, I recommend you to go through Runtime Polymorphism since this post is an extension of the same.

Consider an organization where an Employee can be a Regular Employee or a Consultant. After all, an employee cannot be just an employee. An employee is under one of these categories. To simulate these types of cases in OOP, we make use of abstract classes in Java.

An abstract method (pure virtual function in C++) doesn’t contain a body. An abstract method must be overridden in subclass. Otherwise, the subclass will become abstract.

A class having one or more abstract functions can be declared as an abstract class. We cannot create an object for an abstract class. However, an object reference for an abstract class can be created. Now you may doubt the use of creating a class without an object. For example, in the above example, an object of the Employee class should not be created since an employee cannot just be an employee. Such types of classes should be defined as abstract classes. Now if we allow the objects to be created for an Employee class, it might lead to extra memory usage and also might defeat the very purpose of runtime polymorphism. But we can create an object reference of Employee and point it to an object of its subclass. This is where runtimepolymorphism again comes into picture. In the previous post, you must have already read the golden rule of Runtime Polymorphism: “An object reference of a super class can always point to an object of a subclass.” Instead of the super class object reference pointing to an object of subclass, we now make the abstract class object reference pointing to an object of a subclass.

The implementation for Employee Class is given below.


The implementation for RegularEmployee class is given below.



The implementation for Consultant class is given below.



You can observe that the abstract method in the superclass is overridden in both the above subclasses. Now we will see how runtime polymorphism can be applied using abstract classes.



A class can be declared as an abstract class even though it doesn’t contain any abstract methods. This can be used in situations where there are no abstract functions to be overridden in the subclasses, but at the same time, the abstract class should not have an object.

An abstract class can contain other non-abstract members such as methods and instance variables.

Related Posts:

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...