Home > Back-end >  Programming questions in
Programming questions in

Time:10-07

Programming: define an abstract class Shape, it contains two abstract methods area (), and generating (), derived from the Shape class Circle and Rectangle, these two classes are in area () method to calculate the area, with generating () method to calculate the perimeter, writing applications using Circle and Rectangle, to test,

CodePudding user response:

Shape abstract class
Public interface IShape {

Double area ();

Double generating ();
}

Circle to achieve shape
Public class Circle implements IShape {

Private double r;

Public Circle (double r) {
This. R=r;
}

@ Override
Public double area () {
Return Math. PI * r * r;
}

@ Override
Public double generating () {
Return Math. PI * r * 2;
}
}

A rectangle shape abstract class
Public class Rectangle implements IShape {

Private double width;

Private double length;

The public a Rectangle (double width, double length) {
This. Width=width;
This. Length=length;
}

@ Override
Public double area () {
Return the width * length;
}

@ Override
Public double generating () {
Return 2 * (width and length);
}
}

The test class, as well as test results
Package shape;

Public class Test {

Public static void main (String [] args) {
IShape shape=new Circle (2.3);
System. The out. Println (" circular area: "+ shape. Area ());
System. The out. Println (" circular perimeter: "+ shape. Generating ());

Shape=new Rectangle (2, 3);
System. The out. Println (" rectangle area: "+ shape. Area ());
System. The out. Println (" rectangular circumference: "+ shape. Generating ());
}
}

Test case results
A circular area: 16.619025137490002
Round the perimeter: 14.451326206513047
Rectangular area: 6.0
Rectangular circumference: 10.0



  • Related