Abstract Class in Java
Java Object Oriented Programming Core – Part 12
Forward: In this part of the series, I talk about abstract classes in Java.
By: Chrysanthus Date Published: 3 Sep 2012
Introduction
Syntax for Abstract Class
The syntax for an abstract class is:
abstract [public] Classname
{
//properties
//methods, which may or may not be abstract
}
Abstract Method
The syntax for an abstract method is:
abstract methodSignature;
Any class that has any abstract method, must be declared as abstract. In other words, any class that has any abstract method must be preceded by the reserved word, abstract.
The following code illustrates the declaration and use of abstract class and method.
abstract class Calculator
{
//some properties
abstract protected int add(int para1, int para2);
}
class Calc extends Calculator
{
protected int add(int para1, int para2)
{
int sum = para1 + para2;
return sum;
}
}
class AbstractEx
{
public static void main(String[] args)
{
Calc obj = new Calc();
int result = obj.add(2,3);
System.out.println(result);
}
}
You implement a method in the subclass by just declaring (typing) it completely beginning from the method signature. However, do not type the semicolon after the first line of the declaration. Do not also type the preceding reserved word, abstract. In addition, the modifier (e.g. protected) in the subclass must be of the same access level or higher.
Reason for Abstract Class
You may write a class today, you know the method, but you have not yet decided on the method implementation. In that case you create the abstract class. In future you implement the method. In some cases, the method might even be implemented by a different person. It is also possible that with time, the implementation code may be changed; in that case, the (super) class structure is left intact and not affected.
That is it for this part of the series.
End of Series
We have come to the end of the series. I hope you appreciate it. In this series I have given you the core of Java programming. Click the link named, "Java Course", below to know the series to continue with, next.
Chrys