Java 面向对象编程:Shape 抽象类和圆形、正方形、长方形子类实现
Java 面向对象编程:Shape 抽象类和圆形、正方形、长方形子类实现
本文将使用 Java 语言演示如何通过抽象类和子类实现圆形、正方形、长方形的面积计算,并提供完整的代码示例。
1. 抽象类 Shape
首先定义一个抽象类 Shape,它包含一个抽象方法 getArea() 用于计算面积。
public abstract class Shape {
public abstract double getArea();
}
2. 圆形子类 Circle
Circle 类继承自 Shape,并实现 getArea() 方法,用于计算圆形的面积。
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
3. 正方形子类 Square
Square 类继承自 Shape,并实现 getArea() 方法,用于计算正方形的面积。
public class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
@Override
public double getArea() {
return side * side;
}
}
4. 长方形子类 Rectangle
Rectangle 类继承自 Shape,并实现 getArea() 方法,用于计算长方形的面积。
public class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
5. 代码示例
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape square = new Square(4.0);
Shape rectangle = new Rectangle(3.0, 6.0);
System.out.println("圆形的面积:" + circle.getArea());
System.out.println("正方形的面积:" + square.getArea());
System.out.println("长方形的面积:" + rectangle.getArea());
}
}
总结
通过抽象类和子类,我们成功地实现了圆形、正方形、长方形的面积计算。这种面向对象编程思想,可以有效地提高代码的可读性和可维护性,并方便我们进行扩展。
原文地址: https://www.cveoy.top/t/topic/nwh6 著作权归作者所有。请勿转载和采集!