【JAVA SE】『抽象类』和『接口』的区别

温馨提示

大家好我是Cbiltps,在我的博客中如果有难以理解的句意难以用文字表达的重点,我会有配图。所以我的博客配图非常重要!!!

本节的知识点是从我的主体博客中抽出来的,主体博客其实就是起到一个拓展上下文,为所有的知识点体现逻辑顺序的作用。所以,我会把里面有讨论价值的东西单独拉出来,方便大家食用!

欢迎大家指正/补充,加油!

正文开始

抽象类: 一个类被 abstract 修饰,就直接叫抽象类(定义不重要!)

  • 抽象类不能直接实例化(会直接报错)

  • 抽象类中可以有普通的方法和成员

  • 普通类继承了抽象类,这个普通类中必须重写抽象类的所有抽象方法(可以被重写和调用)

  • 抽象方法不能是 private 修饰的

  • 一个抽象类B继承了抽象类A,那么这个抽象类A中可以不实现抽象类A的抽象方法!

  • 在上条继承关系的基础上,普通类C继承了抽象类B,那么A和B中的抽象方法必须被重写!

  • 抽象类和抽象方法是不能被 final 修饰!

Interface: In a class, methods with the same name are considered overloaded if they have different parameter lists ( different parameter types , different numbers of parameters , or even different order of parameters ). At the same time, overloading has no requirement on the return type , which can be the same or different, so the overload cannot be judged by whether the return type is the same .

  • Interfaces cannot be instantiated by themselves
  • The methods contained in the interface are all 抽象方法, and the fields can only contain 静态常量!
  • Ordinary methods in interfaces cannot have specific implementations . If you want to implement them, you must use the default keyword to modify this method!
  • An interface can have a static method , and this static method can have a method body
  • The method in the interface must be an abstract method , so abstract can be omitted
  • The method in the interface must be public , so the public can be omitted

Note and difference summary:

  • Neither can be instantiated individually
  • Abstract classes use the extends keyword to inherit abstract classes; subclasses use the keyword implements to implement interfaces
  • Abstract methods can have modifiers such as public , protected , and default ; interface methods have the default modifier of public , and other modifiers cannot be used.
  • Abstract classes can only be single- inherited ; interfaces can be implemented in multiple ways
  • There can be ordinary methods and members in the abstract class ; the methods contained in the interface are all 抽象方法, and the fields can only contain 静态常量!

insert image description here

Guess you like

Origin blog.csdn.net/Cbiltps/article/details/122550331