zl程序教程

您现在的位置是:首页 >  工具

当前栏目

抽象类vs接口

vs接口 抽象类
2023-06-13 09:13:35 时间

区别

  1. 抽象类的方法可以有方法体,而接口的方法不允许有方法体
  2. 抽象类中方法,如果没有加abstract修饰,必须定义方法体
  3. 类可以实现多个接口,但是只能继承一个抽象类
  4. 接口的方法都是public的,而抽象类可以自己设置权限。但是抽象类的抽象方法不能设置成private。
  5. 接口的成员必须初始化,而抽象类的不需要
  6. 抽象类可以实现接口,而接口不能实现接口

例子

public interface Car {
	int price = 1;
	void run();
}

public abstract class AbstractCar {
	int price;
	public void run(){
		System.out.println("hh");
	}
	abstract void stop();
}

应用场景

  • An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
  • An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
  • If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
  • Interfaces are a good choice when you think that the API will not change for a while.
  • Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.