Abstract classes are used in Object Oriented Programming languages like Java. An abstract class, in terms of implementation, is somewhere between an implementation class and an interface.
What is an abstract class?
Let us figure out what is an abstract class. Let us assume that you have a base class called BaseClass and a derived class DerivedClass that is the implementation class and is a sub-class of BaseClass.
public class BaseClass {
BaseClass(){}
public void defaultMethod_1(){
}
public void dummyMethod_1(){
}
}
public class DerivedClass extends BaseClass {
public void dummyMethod_1() {
}
}
Now say, you want the following
- BaseClass needs to have implementation for some of its object methods (let us call them Default methods). So that the DerivedClass need not override them, if they don’t want any other behavior.
- BaseClass have some of the methods (let us call them Dummy Methods) which, it STRICTLY want all of its child classes to override. Infact, the BaseClass wants to throw an error, if they don’t override these methods.
- BaseClass is too generic a class (like a Vehicle Class) and it does not make any sense to create an object of it by calling
newBaseClass()
All the initialization should be done through the subclasses. The above implementation of the BaseClass and DerivedClass clearly will not help us in achieving these. One modification to support (1) and (2) may be to throw UnSupportedOperationException() from the dummy methods of BaseClass.
public void dummyMethod_1(){
throw new UnsupportedOperationException();
}
But they have the following issues.
- They will be found only during the run time and not at compile time.
- You cannot use UnSupportedOperationException in case of BaseClass constructor to prevent calling the BaseClass constructor directly. Because this constructor gets called even when you are calling a DerivedClass constructor using
|
BaseClass bc =newDerivedClass(); |
In fact, it will be the first one to get called.
How to achieve all the three requirements
All the above three requirements can be achieved by modifying the BaseClass to have the dummy methods as abstract methods and make it an abstract class. So here is what you have to do to the BaseClass(you need to modify only the base class
- All the dummy methods will have the keyword ‘abstract’. These methods will not have any method bodies but will have only declaration.
- If you have more than one abstract methods in a class, then Java does not allow the instantiation of objects of this class. Java achieves this by making sure at compile time that all the classes which have more than one abstract methods, will be abstract classes.
public abstract class BaseClass {
BaseClass(){
}
public void defaultMethod_1(){
}
public abstract void dummyMethod_1();
}