一、抽象类
(一)定义与特点
抽象类是 Java 中一种特殊的类,它不能被直接实例化,必须被继承。抽象类可以包含抽象方法(没有实现的方法)和具体方法(有实现的方法)。抽象类使用 abstract
关键字修饰。
abstract class Animal {
// 抽象方法
abstract void makeSound();
// 具体方法
void eat() {
System.out.println("Eating...");
}
}
(二)子类继承抽象类
子类继承抽象类时,必须实现抽象类中的所有抽象方法,除非子类本身也是抽象类。
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark!");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow!");
}
}
(三)使用抽象类
通过抽象类,我们可以定义一个通用的模板,让不同的子类按照这个模板实现具体的功能。
public class AbstractClassExample {
public static void main(String[] args) {
Animal dog = new Dog();
dog.makeSound(); // 输出:Bark!
dog.eat(); // 输出:Eating...
Animal cat = new Cat();
cat.makeSound(); // 输出:Meow!
cat.eat(); // 输出:Eating...
}
}
二、接口
(一)定义与特点
接口是 Java 中一种完全抽象的类型,它定义了一组方法规范,但不提供具体实现。接口使用 interface
关键字定义,从 Java 8 开始,接口可以包含默认方法和静态方法。
interface Drawable {
// 抽象方法
void draw();
// 默认方法
default void resize(int width, int height) {
System.out.println("Resizing to " + width + "x" + height);
}
// 静态方法
static void printInfo() {
System.out.println("Drawable interface");
}
}
(二)类实现接口
类通过 implements
关键字实现接口,必须实现接口中的所有抽象方法。
class Circle implements Drawable {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle implements Drawable {
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
(三)使用接口
接口用于定义对象的契约,不同的类可以按照这个契约实现具体的功能。
public class InterfaceExample {
public static void main(String[] args) {
Drawable circle = new Circle();
circle.draw(); // 输出:Drawing a circle
circle.resize(100, 200); // 输出:Resizing to 100x200
Drawable rectangle = new Rectangle();
rectangle.draw(); // 输出:Drawing a rectangle
Drawable.printInfo(); // 输出:Drawable interface
}
}
三、抽象类与接口的区别
- 继承与实现:抽象类通过
extends
关键字继承,接口通过implements
关键字实现。 - 方法实现:抽象类可以包含具体方法,接口在 Java 8 之前只能包含抽象方法。
- 多继承:类只能继承一个抽象类,但可以实现多个接口。
- 默认方法:接口从 Java 8 开始支持默认方法和静态方法,抽象类可以包含任意类型的方法。
四、总结
抽象类和接口是 Java 面向对象编程中的重要概念。抽象类用于定义一个通用的模板,包含可以有实现的方法;接口用于定义一组方法规范,支持多继承。在实际开发中,根据具体需求选择使用抽象类或接口,可以更好地组织代码结构,提高代码的可维护性和扩展性。