Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

普通类,抽象类,接口有哪些区别? #235

Open
zhonghuasheng opened this issue Apr 1, 2020 · 0 comments
Open

普通类,抽象类,接口有哪些区别? #235

zhonghuasheng opened this issue Apr 1, 2020 · 0 comments
Labels

Comments

@zhonghuasheng
Copy link
Owner

  1. 普通类可以去实例化调用,抽象类不能被实例化
  2. 普通类和抽象类都可以被继承,但是抽象类被继承后子类必须重写抽象类中的抽象方法,除非自己也是抽象类
  3. 抽象类可以有具体的方法和属性,接口只能有抽象方法和不可变的常量
  4. 抽象类和接口性质不同,抽象类是对对象的抽象,接口是一种行为规范
  5. 什么时候使用抽象类,什么时候使用接口
    使用接口:
  • 需要让不相关的类都实现一个方法,例如不相关的类都可以实现 Compareable 接口中的 compareTo() 方法;
  • 需要使用多重继承。
    使用抽象类:
  • 需要在几个相关的类中共享代码。
  • 需要能控制继承来的成员的访问权限,而不是都为 public。
  • 需要继承非静态和非常量字段。
    在很多情况下,接口优先于抽象类。因为接口没有抽象类严格的类层次结构要求,可以灵活地为一个类添加行为。并且从 Java 8 开始,接口也可以有默认的方法实现,使得修改接口的成本也变的很低。
    另外有一点是接口中有一个叫做标记接口,例如RandomAccess
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant