Abstract methods are those which need to be implemented in subclass / child class. Abstract methods are only defined in superclass / parent class but with no body.
Syntax of Abstract Method
abstract class clsName
{
// Variable declaration
// Constructor
// Method
abstract rtype mthName(params);
}
clsName is a valid identifier in java. It is a class name.
abstract is a keyword to define that method an abstract method.
rtype is return type of a method.
mthName is a method name and valid java identifier.
Example of an Abstract Method
Example 1 : Program that illustrates the use of an abstract method
abstract class Shape
{
public static float pi = 3.142;
protected float height;
protected float width;
abstract float area();
}
class Square extends Shape
{
Square(float h, float w)
{
height = h;
width = w;
}
float area()
{
return height * width;
}
}
class Rectangle extends Shape
{
Rectangle(float h, float w)
{
height = h;
width = w;
}
float area()
{
return height * width;
}
}
class Circle extends Shape
{
float radius;
Circle(float r)
{
radius = r;
}
float area()
{
return Shape.pi * radius *radius;
}
}
class AbstractMethodDemo
{
public static void main(String args[])
{
Square sObj = new Square(5,5);
Rectangle rObj = new Rectangle(5,7);
Circle cObj = new Circle(2);
System.out.println("Area of square : " + sObj.area());
System.out.println("Area of rectangle : " + rObj.area());
System.out.println("Area of circle : " + cObj.area());
}
}
Output
Area of square : 25
Area of rectangle : 35
Area of circle : 12.57