Write a program that defines an abstract class "Shape" that contains two methods to calculate the circumference and area. Then define two subclasses, Rectangle (Rect), and Circle (circle). The rectangle has a long and wide property, and the circle has a RADIUS attribute, but the two classes implement the circumference and computational area method in the abstract class.
Write the test class to test the above class.
1. Define an abstract class "Shape" that contains two methods to calculate the circumference and area.
Packagecom.shen.shape; // defines an abstract class "Shape" that contains two methods to calculate the circumference and area. // calculate perimeter // calculate area }
2. Define a subclass Rectangle (Rect) that inherits from the abstract class "Shape"
Packagecom.shen.shape;//defines a subclass rectangle (Rect) that inherits from the abstract class "Shape"publicclassrectextends shape{privatedoublewidth;//the length of the rectanglePrivatedoubleheight;//width of the rectangle//constructor FunctionPublicrect (DoubleWidthDoubleheight) { Super(); This. width =width; This. Height =height; } //find the perimeter of a rectangle@Override publicdoublegetcircumference () {//TODO auto-generated Method Stub return(width+height)/2.0; } //to find the area of a rectangle@Override Publicdoublegetarea () {//TODO auto-generated Method Stubreturnwidth*height; }}
3. Defining a Subclass Circle (circle) inherits from the abstract class "Shape"
Packagecom.shen.shape;//Defining a subclass Circle (circle) inherits from the abstract class "Shape"Publicclass Circleextendsshape{Privatedoubler;//radius of the circle//constructor Function PublicCircle (Doubler) {Super(); This. R =R; } //to find the circumference of a circle@Override publicdoublegetcircumference () {//TODO auto-generated Method Stub return2*math.pi*R; }//to find the area of a circle@Override Publicdoublegetarea () {//TODO auto-generated Method Stubreturnmath.pi*r*0; }}
4. Define a test class main to test the above class.
Packagecom.shen.shape;//This is a test class mainpublicclass Main {/*** @paramargs*/publicstaticvoid Main (string[] args) {//TODO auto-generated Method Stub//test the Rectangle class to find the perimeter and area of the rectangleRectrect=newrect (5, 6); System.out.println ("The length is 5, the width is 6 the circumference of the rectangle is:" +rect.getcircumference ()); System.out.println (The area of the rectangle with a length of 5 and a width of 6 is: "+Rect.getarea ()); //test the Circle class to find the circumference and area of the circleCircle circle=NewCircle (5); System.out.println ("\ n the circumference of a circle with a radius of 5 is:" +circle.getcircumference ()); System.out.println (The area of the circle with a radius of 5 is: "+Circle.getarea ()); }}
5. The results are as follows:
Java Abstract class