Java 继承的迷宫:导航超类、子类和多态

在 Java 继承中,超类(父类)是通用类,定义了对象的行为和属性,而子类(派生类)从超类继承并扩展其功能。子类可以使用超类的非私有成员,并可以覆写超类的方法。

多态:

多态性允许一个对象的行为根据其实际类型而变化。在 Java 中,子类对象可以被分配给超类对象,当调用超类方法时,实际执行的方法取决于对象的实际类型。

多态的优点:

多态的挑战:

最佳实践:

常见误解:

示例:

考虑以下示例:

class Shape {
protected String name;

public void draw() {
System.out.println("Drawing a shape");
}
}

class Rectangle extends Shape {
public void draw() {
super.draw();
System.out.println("Drawing a rectangle");
}
}

class Circle extends Shape {
public void draw() {
super.draw();
System.out.println("Drawing a circle");
}
}

public class Main {
public static void main(String[] args) {
Shape s1 = new Rectangle();
Shape s2 = new Circle();

s1.draw(); // Prints "Drawing a rectangle"
s2.draw(); // Prints "Drawing a circle"
}
}

在这个示例中,Shape 是超类,定义了通用行为和属性。RectangleCircle 是从 Shape 继承的子类,它们扩展了 Shape 的行为。main 方法创建两个 Shape 对象,一个分配给 Rectangle,另一个分配给 Circle。当调用 draw() 方法时,执行的实际方法取决于对象的实际类型,展示了多态性。