抽象类vs接口
2023-06-13 09:13:35 时间
区别
- 抽象类的方法可以有方法体,而接口的方法不允许有方法体
- 抽象类中方法,如果没有加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 Code+Git 操作(vs code中git的相关配置与使用)
- BBR vs BBRplus vs BBR2 一般网络速度对比
- Java Vs小游戏
- (StateFlow & ShareFlow) VS (Flow & LiveData)
- IDEA 公司再发新神器!超越 VS Code 骚操作
- vs2019配置opencv什么版本_vs配置opencv
- 【3D人脸】Mediapipe Vs Persona
- Solidity vs Move vs Rust: 智能合约编程语言的演变
- 程序员必备的VS调试技巧
- 使用VS连接 SQL Server数据库的简单指南(vs连接sqlserver)
- VS如何连接Oracle数据库?(vs如何连接oracle)
- VS连接Oracle数据库:一步搞定(vs连oracle数据库)
- Linux VS 苹果:开启科技新世界(linux苹果)
- VS开发环境下MySQL教程简易指南(vs使用mysql教程)
- 硬核观察 | 微软的 VS Code 有 1400 万用户,而全球开发者才 2400 万
- VS如何进行远程调试Linux:详细指南(vs远程调试linux)
- 比较VS选择:如何选择最佳的MySQL驱动程序?(vsmysql驱动)
- 提供安全服务【使用VS保障SQL Server安全性】(vs给sqlserver)
- VS与SQLserver:搭建强大的开发体系(vs与sqlserver)
- VS中SQL Server的完美遇见(vs中sqlserver)
- VS与SqlServer联手构建可靠的数据库运行环境(SqlServer和vs)
- 缓存 vs Redis不同的性能特征(缓存和redis的区别)
- VS编译Redis从零开始(vs编译redis)
- VS开发环境再无Redis踪影(vs中没有redis了)
- VS操作Redis 简单而不繁琐(在vs操作redis)
- VS中如何优雅地操作Redis(vs操作redis)
- VS控制台操作Redis一个非常简单的新手指南(vs控制redis)
- Oracle与VS插件的竞技之战(oracle vs插件)
- 调试Javascript代码(浏览器F12及VS中debugger关键字)