抽象类的特点:
抽象类是一种抽象的类,不能直接实例化,只能用来继承。抽象类中可以包含抽象方法和非抽象方法,抽象方法是没有实现的方法,需要子类去实现。非抽象方法可以有实现,也可以没有实现。如果一个类继承了抽象类,那么它必须实现抽象类中的所有抽象方法。
接口的特点:
接口是一种抽象的类型,与抽象类类似,但是接口中只能包含抽象方法和常量。接口中的抽象方法也没有实现,需要被实现类去实现。常量是指接口中的变量必须是 final 和 static 的。如果一个类要实现某个接口,那么它必须实现接口中的所有抽象方法。
它们的相同点:
- 都不能实例化。
- 都可以被继承或实现。
- 都可以包含抽象方法。
它们的不同点:
- 抽象类可以包含非抽象方法,但是接口中只能包含抽象方法和常量。
- 一个类只能继承一个抽象类,但是可以实现多个接口。
- 抽象类中的抽象方法可以有 public 、protected 和 default 修饰符,但是接口中的抽象方法必须是 public 修饰符。
- 接口中的方法默认是 public 和 abstract 的,而抽象类中的方法可以有多种修饰符。
抽象类的例子:
abstract class Animal {
public abstract void eat(); // 抽象方法
public void walk() { // 非抽象方法
System.out.println("走路");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Dog();
animal.eat();
animal.walk();
}
}
接口的例子:
interface Animal {
void eat(); // 抽象方法
}
interface Flyable {
void fly(); // 抽象方法
}
class Bird implements Animal, Flyable {
public void eat() {
System.out.println("吃虫子");
}
public void fly() {
System.out.println("飞翔");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Bird();
Flyable flyable = new Bird();
animal.eat();
flyable.fly();
}
}