前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >抽象类vs接口

抽象类vs接口

作者头像
jiewuyou
发布2022-09-29 15:00:21
2220
发布2022-09-29 15:00:21
举报
文章被收录于专栏:数据人生

区别

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

例子

代码语言:javascript
复制
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.
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-07-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 区别
  • 例子
  • 应用场景
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档