抽象类与抽象方法
定义抽象类及实现抽象方法
抽象类使用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 Comparable<Person> { String name; Person(String name) { this.name = name; } @Override public int compareTo(Person p) { return this.name.compareTo(p.name); } }Comparator:外部定义排序规则,灵活实现多字段排序。
class AgeComparator implements Comparator<Person> { @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实现多态和设计灵活架构的核心工具。抽象类侧重模板复用,接口侧重行为约定。通过合理选择,可构建高扩展性的系统。