在Java中,抽象类(Abstract Class)和接口(Interface)是两种用于实现抽象和多态的机制。它们有相似之处,但也有显著的区别。
1.抽象类
抽象类是用 abstract
关键字修饰的类。它可以包含抽象方法(没有方法体的方法)和具体方法(有方法体的方法)。抽象类不能被实例化,只能被继承。抽象类可以包含成员变量、构造方法、普通方法和抽象方法。子类继承抽象类时,必须实现所有的抽象方法(除非子类也是抽象类)。抽象类可以有 public
、protected
或 default
访问修饰符。
2.接口
接口是用 interface
关键字定义的,它只能包含抽象方法。接口不能包含成员变量(只能是常量)和构造方法。一个类可以实现多个接口。
//抽象类和接口
//工厂抽象类,有抽象生产方法,两个子类汽车和鞋,汽车厂生产汽车,鞋厂生产鞋
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner input =new Scanner(System.in);
Car a=new Car();
a.product();
Shoes b=new Shoes();
b.product();
}
}
abstract class Gongchang{
}
//设置接口,接口里有抽象方法product
interface method{
public void product();
}
class Car extends Gongchang implements method{
//实现接口
public void product(){System.out.println("汽车厂生产汽车");
}
}
class Shoes extends Gongchang implements method{
//实现接口
public void product(){
System.out.println("鞋厂生产鞋");
}
}
运行结果: