用java实现以下要求1.定义父类class Shape{ String name; public void showName(){...........} } 2. 定义子类:圆形,三角形,矩形,包含求周长,求面积等公式; 3. 定义一个Main类,在其main函数中,用这三个子类创建对象,求其面积,周长等; 4. 请在Main类中定义参数为Shape类型的函数: static void showArea(Shape shape) {.............} static void showPerimeter(Shape shape){..............} 将三角形,圆形,矩形的对象传入,理解面向对象的深刻含义
时间: 2023-06-11 09:06:44 浏览: 118
使用java实现面向对象
以下是Java代码实现:
```
class Shape {
String name;
public void showName() {
System.out.println("图形名称:" + name);
}
}
class Circle extends Shape {
double radius;
public Circle(String name, double radius) {
this.name = name;
this.radius = radius;
}
public void showArea() {
double area = Math.PI * radius * radius;
System.out.println("圆形面积:" + area);
}
public void showPerimeter() {
double perimeter = 2 * Math.PI * radius;
System.out.println("圆形周长:" + perimeter);
}
}
class Triangle extends Shape {
double a;
double b;
double c;
public Triangle(String name, double a, double b, double c) {
this.name = name;
this.a = a;
this.b = b;
this.c = c;
}
public void showArea() {
double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
System.out.println("三角形面积:" + area);
}
public void showPerimeter() {
double perimeter = a + b + c;
System.out.println("三角形周长:" + perimeter);
}
}
class Rectangle extends Shape {
double length;
double width;
public Rectangle(String name, double length, double width) {
this.name = name;
this.length = length;
this.width = width;
}
public void showArea() {
double area = length * width;
System.out.println("矩形面积:" + area);
}
public void showPerimeter() {
double perimeter = 2 * (length + width);
System.out.println("矩形周长:" + perimeter);
}
}
public class Main {
static void showArea(Shape shape) {
shape.showArea();
}
static void showPerimeter(Shape shape) {
shape.showPerimeter();
}
public static void main(String[] args) {
Circle circle = new Circle("圆形", 3.0);
Triangle triangle = new Triangle("三角形", 3.0, 4.0, 5.0);
Rectangle rectangle = new Rectangle("矩形", 4.0, 5.0);
circle.showName();
circle.showArea();
circle.showPerimeter();
triangle.showName();
triangle.showArea();
triangle.showPerimeter();
rectangle.showName();
rectangle.showArea();
rectangle.showPerimeter();
showArea(circle);
showArea(triangle);
showArea(rectangle);
showPerimeter(circle);
showPerimeter(triangle);
showPerimeter(rectangle);
}
}
```
上述代码中,通过定义一个`Shape`父类和三个子类`Circle`、`Triangle`和`Rectangle`,分别实现了求面积和周长的方法。在`Main`类中,创建了三个子类的对象,并且调用了它们的方法,输出了它们的面积和周长。同时,定义了两个参数为`Shape`类型的静态方法`showArea`和`showPerimeter`,可以接收任何一个`Shape`类型的对象,实现了多态的特性,体现了面向对象的深刻含义。
阅读全文