接口 vs 抽象类
发布: (2026年1月18日 GMT+8 13:24)
2 min read
原文: Dev.to
Source: Dev.to
接口还是抽象类?
它们非常相似,因此在何时使用哪一个可能会让人困惑。本文将回答这个问题。
简短回答
在以下情况下使用接口…
- 没有默认行为
- 你想强制子类(实现)实现该行为
在以下情况下使用抽象类…
- 你想定义默认行为
- 你想控制流程的执行顺序,而具体的步骤由子类实现
代码示例
接口
public interface IAnimal {
void bark();
}
public class Dog implements IAnimal {
@Override
public void bark() {
System.out.println("woof!");
}
}
public static void main(String[] args) {
IAnimal dog = new Dog();
dog.bark(); // "woof!"
}
因为叫声取决于具体动物,IAnimal 并未提供默认行为。子类别无选择,只能覆盖 bark 方法,否则会导致编译错误。
抽象类
public abstract class Animal {
// The method is final to prevent subclasses from changing the order in which methods are called
public final void bark() {
takeBreath();
makeSounds();
}
// private method as implementation is common for all the animals
private void takeBreath() {
System.out.println("taking a deep breath...");
}
// protected so that subclasses can override while client (main method) cannot call this method directly
// abstract method to force subclasses to implements this method
protected abstract void makeSounds();
}
public class Cat extends Animal {
@Override
public void makeSounds() {
System.out.println("meow!");
}
}
public static void main(String[] args) {
Animal car = new Cat();
cat.bark(); // "meow!"
}
我想控制 makeSounds 的流程,使所有动物先呼吸再叫;这个流程应保持不变。然而,和前面的例子一样,叫声取决于具体动物,所以 bark 方法应由子类实现。