用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 19:06:40 浏览: 146
使用java实现面向对象
以下是Java代码实现:
```
// Shape.java
public class Shape {
String name;
public void showName() {
System.out.println("This is a " + name);
}
}
// Circle.java
public class Circle extends Shape {
double radius;
public Circle(double radius) {
this.radius = radius;
this.name = "Circle";
}
public void showArea() {
double area = Math.PI * radius * radius;
System.out.println("The area of the circle is " + area);
}
public void showPerimeter() {
double perimeter = 2 * Math.PI * radius;
System.out.println("The perimeter of the circle is " + perimeter);
}
}
// Triangle.java
public class Triangle extends Shape {
double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
this.name = "Triangle";
}
public void showArea() {
double p = (a + b + c) / 2;
double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
System.out.println("The area of the triangle is " + area);
}
public void showPerimeter() {
double perimeter = a + b + c;
System.out.println("The perimeter of the triangle is " + perimeter);
}
}
// Rectangle.java
public class Rectangle extends Shape {
double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
this.name = "Rectangle";
}
public void showArea() {
double area = width * height;
System.out.println("The area of the rectangle is " + area);
}
public void showPerimeter() {
double perimeter = 2 * (width + height);
System.out.println("The perimeter of the rectangle is " + perimeter);
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5);
Triangle triangle = new Triangle(3, 4, 5);
Rectangle rectangle = new Rectangle(6, 8);
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);
}
static void showArea(Shape shape) {
shape.showArea();
}
static void showPerimeter(Shape shape) {
shape.showPerimeter();
}
}
```
这个程序中,我们定义了一个父类 `Shape`,它包含一个 `name` 属性和一个 `showName` 方法。我们还定义了三个子类 `Circle`、`Triangle` 和 `Rectangle`,它们分别实现了求周长和面积的公式,并且在构造函数中设置了 `name` 属性。
在 `Main` 类中,我们创建了三个对象,分别是圆形、三角形和矩形,并且调用它们的 `showName`、`showArea` 和 `showPerimeter` 方法来打印它们的名称、面积和周长。
同时,我们还定义了两个静态方法 `showArea` 和 `showPerimeter`,它们的参数为 `Shape` 类型。这充分体现了面向对象的思想,我们可以将圆形、三角形和矩形的对象传入这两个方法中,它们都能正常工作。这是因为我们定义了一个父类 `Shape`,并且在子类中实现了父类中的方法,符合面向对象的封装、继承和多态的原则。
阅读全文