异同点:
子类继承父类(Inheritance) :
-
引用关键字:
extends
。 -
子类继承父类的所有非私有成员(字段和方法),包括构造方法。
-
子类可以使用父类的非私有成员,不需要重新定义。
-
一个子类只能继承一个父类,Java不支持多重继承(一个类继承多个父类)。
-
继承是为了实现"is-a"关系,子类是父类的一种特殊类型。
实现抽象类(Abstract Class):
-
使用关键字:
extends
用于继承普通类,implements
用于实现接口或抽象类。 -
抽象类是不能被实例化的,只能用作其他类的基类。
-
抽象类可以包含抽象方法和非抽象方法。抽象方法没有具体实现,而非抽象方法有具体实现。
-
如果一个类继承了一个抽象类,它必须实现抽象类中的所有抽象方法,除非它自己也声明为抽象类。
-
一个类可以实现多个接口,Java支持多重实现(一个类实现多个接口)。
// 继承父类的示例
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
// 实现抽象类的示例
abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
public abstract double getArea();
public void displayColor() {
System.out.println("Shape color: " + color);
}
}
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.makeSound(); // Output: Dog barks
Circle circle = new Circle("Red", 5.0);
circle.displayColor(); // Output: Shape color: Red
System.out.println("Circle area: " + circle.getArea()); // Output: Circle area: 78.53981633974483
}
}
在上面的示例中,Dog
类继承自Animal
类,而Circle
类实现了抽象类Shape
。在继承父类中,子类继承了父类的属性和方法,并可以通过super
关键字调用父类的构造方法。在实现抽象类中,子类必须实现抽象类中声明的抽象方法,而非抽象方法可以选择性地重写