Abstract class and abstract methods are decorated.
A class that contains an abstract method can only be defined as an abstract class, but there is no abstract method in an abstract class.
There is no method body for abstract methods. Implementations can only be provided by subclasses (Overrides).
Abstract classes can only be inherited, and final decorated classes cannot be inherited, so abstract and final cannot coexist.
The abstract method is as follows:
Public abstract class sharp//abstract classes {
private String color; Public abstract String GetType ();//abstract method
{
SYSTEM.OUT.PRINTLN ("Executing initialization blocks in abstract class sharp");
}
Public Sharp ()
{}
Sharp's constructor, not for the creation of sharp objects, but for the invocation of subclasses
Public Sharp (String color)
{
SYSTEM.OUT.PRINTLN ("The structure of the Sharp class");
This.color = color;
}
}
In the above code, this abstract class contains the initialization block, the constructor.
The following defines a triangle class that inherits the Sharp class and implements the abstract method in the sharp class.
public class Triangle extends sharp{
Define three edges
Private double a,b,c;
Public Triangle (String color,double a,double b,double c)
{
Super (color);
This.a=a;
This.b=b;
This.c=c;
}
Rewrite the abstract method of calculating perimeter in the sharp class
Public double Calperimeter ()
{
return a+b+c;
}
Overriding the abstract method of returning shapes in the sharp class
Public String get Type ()
{
return "triangle";
}
}
Assuming there is another circle class that inherits the Sharp class, the following code:
The main method of the test class is main () {sharp S1 = new Triangle ("Black", 2,3,4);
Sharp s2 = new Circle ("Yellow", 3);
Syso (S1.gettype ());//polymorphic
Syso (S1.calperimeter ());
Syso (S2.gettype ());
Syso (S2.calperimeter ());
}
This code defines a reference variable of 2 sharp types, pointing to triangle and circle, respectively. S1 and S2 can invoke the above method directly without forcing the type to be converted to its subclass.
Note : Using abstract classes and abstract methods can give full play to the advantages of polymorphism, use more flexible.
Abstract classes and abstract methods in Java