Problem: using multi-state programming to create a shape class, we can find the square, triangle, and circle area,
Method: Abstract A Shared parent class, define a function as a public interface for area calculation, and then redefine the area function for each shape. Create objects of different classes in the main class and obtain area of different shapes.
Enter the subject...
Create the following five classes under the same package and run the testshape class!
// Abstract class -- image --------------------------------------
Public abstract class shape {
// Use the abstract method to obtain the image area
Public abstract double getarea ();
}
// The square inherits the graph class -------------------------------
Public class square extends shape {
// Side length of a square
Private double height = 0;
// Constructor
Public Square (double height ){
This. Height = height;
}
// @ Override
Public double getarea (){
Return (this. Height * This. Height); // math. Pow (this. Height, 2 );
}
}
// The Circle inherits the class --------------------------- of the graph -------------------------
Public class circle extends shape {
// Radius of the circle
Private double r = 0;
// Circumference Rate
Private Final Static double Pi = 3.14;
// Constructor
Public circle (double r ){
This. r = R;
}
@ Override
Public double getarea (){
Return (pI * r * R );
}
}
// The class of the triangle inherited graph ------------------------------
Public class triangle extends shape {
// Side 1 of the triangle
Private double A = 0;
// Triangle side 2
Private Double B = 0;
// Triangle side 3
Private double C = 0;
// Triangle height
Private double H = 0;
// Constructor. The height and bottom of a triangle are known.
Public triangle (double A, double H ){
This. A =;
This. H = h;
}
// Constructor. It is known that the length of the triangle is three sides.
Public triangle (double A, double B, double C ){
This. A =;
This. B = B;
This. C = C;
}
@ Override
Public double getarea (){
If (H = 0 ){
// Calculate the area of the triangle according to Helen's Formula
Double S = (A + B + C)/2;
Return math. Pow (S * (S-A) * (S-B) * (s-c), 0.5 );
} Else {
// Normal formula
Return (A * H/2 );
}
}
}
// Test class --------------------------------------------
Public class testshape {
Public static void main (string [] ARGs ){
// Construct a 3-side Square
Shape square = New Square (3 );
// Construct a circle with a radius of 2
Shape Circle = new circle (2 );
// Construct a triangle with a side length of 3, 4, and 5 (according to the stock theorem, we know that it is a right triangle)
Shape triangle1 = New Triangle (3, 4, 5 );
// Construct a triangle with the height and bottom 3 and 4 respectively.
Shape triangle2 = New Triangle (3, 4 );
System. Out. println (square. getarea ());
System. Out. println (circle. getarea ());
System. Out. println (triangle1.getarea ());
System. Out. println (triangle2.getarea ());
}
}
Test results:
9.0
12.56
6.0
6.0