面试题答案
一键面试抽象类实现代码复用的方式
- 定义通用属性和方法:在抽象类中可以定义一些通用的成员变量和方法,这些属性和方法对于其子类来说是公共的部分。子类继承抽象类后,自动拥有这些属性和方法,无需重复编写,从而实现代码复用。
- 抽象方法提供框架:抽象类可以包含抽象方法,抽象方法只有声明没有实现。子类必须实现这些抽象方法,但抽象类定义了整体的行为框架,子类在遵循这个框架的基础上进行具体实现,这样也能避免子类在结构上的重复设计。
示例
// 抽象类
abstract class Shape {
// 通用属性
protected String color;
// 通用方法
public void setColor(String color) {
this.color = color;
}
// 抽象方法
public abstract double getArea();
}
// 子类继承抽象类
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// 实现抽象方法
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// 实现抽象方法
@Override
public double getArea() {
return width * height;
}
}
在上述例子中,Shape
抽象类定义了通用属性 color
和通用方法 setColor
,以及抽象方法 getArea
。Circle
和 Rectangle
子类继承 Shape
抽象类,复用了 color
属性和 setColor
方法,同时各自实现 getArea
方法来符合自身的计算逻辑,避免了重复编写通用部分的代码。