啥时候用抽象类,啥时候用接口【示例】
好的,通过具体示例来理解这个区别:
抽象类示例 - "是什么"关系
// 抽象类:定义"动物是什么"的家族共性
public abstract class Animal {private String name;// 动物共有的具体属性public String getName() { return name; }// 动物共有的具体行为public void breathe() { System.out.println("呼吸中..."); }// 抽象方法:子类必须实现,但每个动物叫法不同public abstract void makeSound();
}// 具体动物:猫"是一种"动物
public class Cat extends Animal {@Overridepublic void makeSound() {System.out.println("喵喵喵");}
}// 具体动物:狗"是一种"动物
public class Dog extends Animal {@Overridepublic void makeSound() {System.out.println("汪汪汪");}
}
接口示例 - "能做什么"关系
// 接口:定义"能飞"的能力(跨物种)
public interface Flyable {void fly();
}// 接口:定义"能游泳"的能力(跨物种)
public interface Swimmable {void swim();
}// 不同的类实现相同接口
public class Bird implements Flyable {@Overridepublic void fly() {System.out.println("鸟用翅膀飞");}
}public class Airplane implements Flyable {@Overridepublic void fly() {System.out.println("飞机用引擎飞");}
}public class Duck extends Animal implements Flyable, Swimmable {@Overridepublic void makeSound() {System.out.println("嘎嘎嘎");}@Overridepublic void fly() {System.out.println("鸭子短距离飞行");}@Overridepublic void swim() {System.out.println("鸭子游泳");}
}
使用场景
public class Test {public static void main(String[] args) {// 抽象类:处理家族关系Animal cat = new Cat();Animal dog = new Dog();cat.makeSound(); // 喵喵喵dog.makeSound(); // 汪汪汪// 接口:处理能力行为Flyable[] flyingThings = {new Bird(), new Airplane(), new Duck()};for (Flyable thing : flyingThings) {thing.fly(); // 不同事物,同样的飞行能力}}
}
一句话总结:
- 用抽象类:猫、狗都是"动物"(是什么)
- 用接口:鸟、飞机、鸭子都能"飞"(能做什么)
