A method with method body is
called concrete method. In general any class will have all concrete methods. A
method without method body is called abstract method. A class that contains
abstract method is called abstract class. It is possible to implement the
abstract methods differently in the subclasses of an abstract class. These
different implementations will help the programmer to perform different tasks
depending on the need of the sub classes. Moreover, the common members of the
abstract class are also shared by the sub classes.
The abstract methods and abstract
class should be declared using the keyword abstract. We cannot create objects
to abstract class because it is having incomplete code. Whenever an abstract
class is created, subclass should be created to it and the abstract methods
should be implemented in the subclasses, then we can create objects to the
subclasses.
· An
abstract class is a class with zero or more abstract methods
· An
abstract class contains instance variables & concrete methods in addition
to abstract methods.
· It
is not possible to create objects to abstract class.
· But
we can create a reference of abstract class type.
· All
the abstract methods of the abstract class should be implemented in its sub
classes.
· If
any method is not implemented, then that sub class should be declared as
‘abstract’.
· Abstract
class reference can be used to refer to the objects of its sub classes.
· Abstract
class references cannot refer to the individual methods of sub classes.
· A
class cannot be both ‘abstract’ & ‘final’.
e.g.: final abstract class
A // invalid
Program 1: Write
an example program for abstract class.
// Using abstract methods and classes.
abstract class Figure
{
double dim1; double
dim2;
Figure (double a, double b)
{ dim1
= a;
dim2
= b;
}
abstract double area (); //
area is now an abstract method
}
class Rectangle extends
Figure
{
Rectangle (double a,
double b)
{ super
(a, b);
}
double
area () // override area for rectangle
{
System.out.println
("Inside Area of Rectangle.");
return
dim1 * dim2;
}
}
class Triangle extends Figure
{ Triangle (double a, double b)
{
super (a, b);
}
double
area() //
override area for right triangle
{
System.out.println
("Inside Area of Triangle.");
return
dim1 * dim2 / 2;
}
}
class AbstractAreas
{ public static void main(String
args[])
{ //
Figure f = new Figure(10, 10); // illegal now
Rectangle
r = new Rectangle(9, 5);
System.out.println("Area
is " + r.area());
System.out.println("Area
is " + t.area());
}
}
Output: