抽象类vs接口
2014-07-31 21:10
155 查看
区别
抽象类的方法可以有方法体,而接口的方法不允许有方法体抽象类中方法,如果没有加abstract修饰,必须定义方法体
类可以实现多个接口,但是只能继承一个抽象类
接口的方法都是public的,而抽象类可以自己设置权限。但是抽象类的抽象方法不能设置成private。
接口的成员必须初始化,而抽象类的不需要
抽象类可以实现接口,而接口不能实现接口
例子
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 抽象类
- 抽象类VS接口
- 抽象类 VS 接口
- 抽象类 vs 接口
- 抽象类VS接口
- 数组VS枚举;类VS结构;抽象类VS接口
- 抽象类 vs 接口(Java)
- 抽象类 VS 接口
- 抽象类VS接口
- .天轰穿C# -vs2010 - 04面向对象的编程之接口 VS 抽象类 【原创】
- Abstract Class VS Interface | 抽象类VS接口
- Java 抽象类 vs 接口
- 深入理解抽象类和接口(abstract class vs interface ) 转 www.IBM.com
- 抽象类vs接口,浅复制Vs深复制
- 接口(interface)vs. 抽象类(abstract class)
- 抽象类VS接口
- 接口(interface)vs. 抽象类(abstract class)
- 抽象类VS接口-浅析
- 韩顺平php视频笔记77 抽象类vs接口 关键字final const
- 接口 vs 抽象类, Trait