1、抽象类(Abstract Class)
抽象类是通过abstract关键字声明的类。
抽象类可以包含抽象方法和具体方法。
抽象类的主要目的是为了被子类继承,并且子类需要实现抽象方法。
抽象类可以有构造方法,但是不能被实例化。
可以使用抽象类的引用来引用其子类的对象。
示例:
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof
myDog.sleep(); // Output: Zzz
}
}
2、 接口(Interface)
接口是通过interface关键字声明的。
接口只能包含常量和抽象方法。
接口的主要目的是定义一种契约,实现类需要遵守这个契约(即实现接口中定义的方法)。
一个类可以实现多个接口。
接口中的方法默认是public和abstract的,可以省略这些修饰符。
示例:
interface Animal {
void makeSound();
void eat();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
public void eat() {
System.out.println("Dog eats");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Output: Woof
myDog.eat(); // Output: Dog eats
}
}