码迷,mamicode.com
首页 > 其他好文 > 详细

抽象类vs接口

时间:2014-08-01 00:10:11      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   java   io   for   2014   

区别

  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.

抽象类vs接口,布布扣,bubuko.com

抽象类vs接口

标签:des   style   blog   color   java   io   for   2014   

原文地址:http://blog.csdn.net/jiewuyou/article/details/38323437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!