Classes from
which objects cannot be instantiated with new operator are called Abstract
Classes. Each abstract class contains
one or more abstract methods. In a class
if there exist any method with no method body is known as abstract method. An abstract method is declared as
Syntax:
abstract type method-name (parameter-list);
“abstract” is a
keyword used for declaring abstract methods.
To declare a class as abstract, use the abstract keyword in front of the
class keyword at the beginning of the class declaration. No objects are created to an abstract
class. For the abstract methods, the
implementation code will be defined in its subclass.
Example:
abstract
class figure
{
double dim1,dim2;
figure(double x,double y)
{
dim1=x;
dim2=y;
}
abstract double area();
}
class
rectangle extends figure
{
rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Rectangle
Area");
return dim1*dim2;
}
}
class
triangle extends figure
{
triangle(double x,double y)
{
super(x,y);
}
double area()
{
System.out.println("Triangle
Area");
return dim1*dim2/2;
}
}
class abs
{
public static void main(String[]
args)
{
//figure obj=new figure(10,10);
//error
rectangle obj1=new rectangle(9,5);
System.out.println("Area="+obj1.area());
triangle obj2=new triangle(10,8);
figure a;
a=obj2;
System.out.println("Area="+a.area());
}
}
Note: 1. We cannot declare any abstract
constructors.
2. Concrete (general) methods are
also being inside any abstract class.
1.
Abstract classes are used for general purposes.
2.
An abstract class must be subclass and override it
methods.
3.
Super class has only method name and signature end with
semicolon.
4.
Abstract classes cannot be used to instantiate objects,
but they can used to create object reference due to Java supports Run-time
Polymorphism.
No comments:
Post a Comment