Pages

SPONSORED

Abstract class and Interface

Abstract Class
Abstract class is a class which cannot be instantiated. We need to inherit this class and then instantiate the child class. Abstract class always acts as base class and contains one or more abstract or non abstract methods. An abstract method is a method that has only definition but not implementation. The child class must provide the definition for all the abstract method of its parent. However if it does not provide the implementation then the child class too must be declared abstract.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

Example
Consider implementing the shapes available under Insert > Shape option of a word document. Some of the properties like fill, border, line style etc are common among all shapes. However other properties must be implemented separately.


We create an abstract class Shape. It is declared abstract as we do not intend to instantiate as shape in general makes no sense. Then create sub classes rectangle, triangle, circle etc.

Interface
Interfaces are used to separate implementation and definitions. It comes to use when the implementations need to be interchangeable and also in cases where the implementation changes frequently.

Interfaces define a generic template and just have method declaration and might contain properties. These method declarations are implicitly public and abstract. Interfaces cannot be instantiated. Interfaces can inherit other interfaces.

A class can implement the interface and implement the methods as per requirement. Each class which implements the interface can implement the method in its own way and can reflect the expected behaviour as per requirement.

In case the class does not implement all the methods from the interface then the class must be declared abstract. This class must be further extended to sub class and implementation must be provided in that sub class. This sub class can be later instantiated and put into use.

Interface definition
public interface Shape
{
//Can have any function which a shape required to be implemented
function area();
}

Implementing the interface
public circle implements shape
{
//Implement the area as required for circle
Function area()
{
                    //calculate area of circle
}
}


The below link has detailed explanation on when to use abstract class and interfaces

 

2 comments: