8.2 abstract class
1). abstract classes and abstract methods
An abstract class is a class modified with an abstract modifier. The syntax format for defining an abstract class is as follows:
Abstract class name
{
Declare member variables;
Method Name of the Data Type returned value (parameter table)
{
......
}
The name of the Data Type method (parameter table) returned by abstract; ------ abstract method. In abstract methods, the method body cannot be defined.
}
Abstract methods are divided into two types: one is the general method previously introduced, and the other is the abstract method ".
The abstract method does not have a method body. Use ";".
The abstract subclass must implement all abstract methods in the parent class, or declare itself as abstract.
An abstract class cannot be modified using final.
2). Application of abstract classes
Eg:
Abstract class shape {
Protected string name;
Public shape (string XM)
{
Name = XM;
System. Out. Print ("name" + name );
}
Abstract Public double getarea (); // declare the abstract Method
Abstract Public double getlength (); // declare an abstract Method
}
Public class circle extends shape
{
Private double Pi = 3.14;
Private double radius;
Public circle (string shapename, Double R)
{
Super (shapename );
Radius = R;
}
Public double getarea ()
{
Return pI * radius;
}
Public double getlength ()
{
Return 2 * pI * radius;
}
}
Public class rectangle extends shape {
Private double width;
Private double height;
Public rectangle (string shapename, double width, double height)
{
Super (shapename );
This. width = width;
This. Height = height;
}
@ Override
Public double getarea (){
Return width * height;
}
@ Override
Public double getlength (){
Return 2 * (width + height );
}
}
Public class app8_10 {
Public static void main (string [] ARGs ){
Shape rect = new rectangle ("rectangles", 6.5, 10.3 );
System. Out. Print ("; Area =" + rect. getarea ());
System. Out. println ("Perimeter =" + rect. getlength ());
Shape Circle = new circle ("circle", 10.2 );
System. Out. Print ("; Area =" + circle. getarea ());
System. Out. println ("; perimeter =" + circle. getlength ());
}
}
Program running result:
Name rectangle; Area = 66.95 perimeter = 33.6
Name circle; Area = 326.68559999999997; perimeter = 64.056