Java继承与高级特性
抽象类与抽象方法定义抽象类及实现抽象方法抽象类使用abstract关键字声明不能直接实例化。抽象类可以包含抽象方法无方法体和具体方法有方法体。子类必须实现所有抽象方法除非子类也是抽象类。abstract class Animal { abstract void makeSound(); // 抽象方法 void sleep() { // 具体方法 System.out.println(Animal is sleeping); } } class Dog extends Animal { Override void makeSound() { // 实现抽象方法 System.out.println(Bark); } }实用案例抽象类常用于定义通用行为模板。例如图形类Shape作为抽象类子类Circle、Rectangle实现具体的calculateArea()方法abstract class Shape { abstract double calculateArea(); } class Circle extends Shape { double radius; Circle(double r) { this.radius r; } Override double calculateArea() { return Math.PI * radius * radius; } }接口接口定义与实现接口通过interface关键字定义所有方法默认是public abstract。类通过implements实现接口必须重写所有方法。interface Drivable { void start(); void stop(); } class Car implements Drivable { Override public void start() { System.out.println(Car started); } Override public void stop() { System.out.println(Car stopped); } }默认方法与静态方法Java 8引入默认方法default和静态方法static允许接口提供方法实现而无需强制子类重写。interface Loggable { default void log(String message) { // 默认方法 System.out.println(Log: message); } static void printVersion() { // 静态方法 System.out.println(Logger v1.0); } } class AppLogger implements Loggable {} // 无需重写默认方法Comparable与Comparator接口Comparable对象自身实现排序逻辑重写compareTo方法。class Person implements ComparablePerson { String name; Person(String name) { this.name name; } Override public int compareTo(Person p) { return this.name.compareTo(p.name); } }Comparator外部定义排序规则灵活实现多字段排序。class AgeComparator implements ComparatorPerson { Override public int compare(Person p1, Person p2) { return p1.age - p2.age; } } // 使用Collections.sort(people, new AgeComparator());实用案例接口常用于多态和插件架构。例如支付系统定义PaymentGateway接口不同支付方式PayPal、Stripe实现统一接口interface PaymentGateway { boolean processPayment(double amount); } class PayPal implements PaymentGateway { Override public boolean processPayment(double amount) { System.out.println(PayPal processing: $ amount); return true; } }高级特性结合应用抽象类与接口对比抽象类适合代码复用包含状态字段和部分实现。接口定义行为契约支持多重继承更灵活扩展。案例游戏角色设计抽象类Character定义公共属性如health接口Attacker和Defender定义角色能力abstract class Character { int health; Character(int health) { this.health health; } } interface Attacker { void attack(Character target); } interface Defender { void defend(); } class Warrior extends Character implements Attacker, Defender { Warrior(int health) { super(health); } Override public void attack(Character target) { target.health - 10; } Override public void defend() { this.health 5; } }总结抽象类与接口是Java实现多态和设计灵活架构的核心工具。抽象类侧重模板复用接口侧重行为约定。通过合理选择可构建高扩展性的系统。