Java 抽象类 Shape:计算图形面积和周长
Java 抽象类 Shape:计算图形面积和周长
本文将使用 Java 抽象类 Shape 来表示图形类,并派生矩形类 Rectangle 和圆类 Circle,分别实现计算面积和周长的方法。
抽象类 Shape
public abstract class Shape {
public abstract float getArea();
public abstract float getPerim();
}
Shape 类是一个抽象类,它定义了两个抽象方法 getArea() 和 getPerim(),分别用于计算图形的面积和周长。由于这两个方法没有具体的实现,因此 Shape 类不能被实例化。
矩形类 Rectangle
public class Rectangle extends Shape {
private float width;
private float height;
public Rectangle(float width, float height) {
this.width = width;
this.height = height;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
@Override
public float getArea() {
return width * height;
}
@Override
public float getPerim() {
return 2 * (width + height);
}
}
Rectangle 类继承了 Shape 类,并实现了 getArea() 和 getPerim() 方法,分别用于计算矩形的面积和周长。
圆类 Circle
public class Circle extends Shape {
private float radius;
public Circle(float radius) {
this.radius = radius;
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
@Override
public float getArea() {
return (float) (Math.PI * radius * radius);
}
@Override
public float getPerim() {
return (float) (2 * Math.PI * radius);
}
}
Circle 类继承了 Shape 类,并实现了 getArea() 和 getPerim() 方法,分别用于计算圆的面积和周长。
通过使用抽象类 Shape,我们可以定义一个通用的图形类,并通过继承和实现其抽象方法来创建不同的图形类型,例如矩形和圆。这种方式可以提高代码的复用性和可扩展性。
原文地址: https://www.cveoy.top/t/topic/nGOX 著作权归作者所有。请勿转载和采集!