Sunday, February 9, 2014

When to Use Abstract Class?

To understand when to use an Abstract Class first let us understand what is abstract class. 

Abstract Class

Abstract Class is a class that cannot be instantiated. In other words, you cannot create an object of abstract class. 

public abstract class Shape{

//some methods and variables

}

Public main class
Shape S1 =  new Shape(); //This entry is invalid as you cannot create object of abstract class.

Abstract class can contain abstract method as well as non abstract methods. Now, these abstract methods can only have declarations.

When a child class inherits abstract class, it must inherit abstract methods in the class.  Parent class has methods with declaration only which are abstract as well as methods with definition also which guarantees that they are being used as it is and cannot be changed. While, methods which are only declared offer flexibility to be used as per requirements of child class. 

When to use an abstract class?

An abstract class must be used when different related components are intended to use set of methods that are functionally same and at the same time offer flexibility to be modified as per needs. You can check examples of abstract class implementation in C# and Java to understand this concept clearly. 

No comments:

Post a Comment

You think post was useful? Feel free to suggest modifications.