Java Bean 类最佳实践:接口、抽象类和具体实现
这是一个简单的标准 Java Bean 类,它具有接口和抽象类:
// 定义接口 interface Shape { double getArea(); }
// 定义抽象类 abstract class TwoDimensionalShape implements Shape { protected double width; protected double height;
public TwoDimensionalShape(double width, double height) { this.width = width; this.height = height; }
@Override public abstract double getArea(); }
// 定义具体类 public class Rectangle extends TwoDimensionalShape { public Rectangle(double width, double height) { super(width, height); }
@Override public double getArea() { return width * height; }
// 定义其他方法 public double getPerimeter() { return 2 * (width + height); }
// 定义 setter 和 getter 方法 public void setWidth(double width) { this.width = width; }
public double getWidth() { return width; }
public void setHeight(double height) { this.height = height; }
public double getHeight() { return height; } }
在上面的代码中,我们首先定义了一个 Shape 接口,它包含一个 getArea() 方法。接着我们定义了一个 TwoDimensionalShape 抽象类,它实现了 Shape 接口,并包含两个实例变量:width 和 height。TwoDimensionalShape 类的构造函数需要传入这两个变量,并且包含一个抽象方法 getArea(),它由 Rectangle 类来实现。
最后,我们定义了一个具体的 Rectangle 类,它继承了 TwoDimensionalShape 抽象类,并实现了 getArea() 方法。Rectangle 类还包含了一个 getPerimeter() 方法和四个 setter 和 getter 方法,用于获取和设置 Rectangle 对象的属性。
原文地址: https://www.cveoy.top/t/topic/nRFe 著作权归作者所有。请勿转载和采集!