[Java] The difference between abstract class and interface

Before JDK8, the definition of interfaces was strict: only variables and abstract methods could be defined, and method bodies could not be written . However, after JDK8 , static methods and default methods can be defined in interfaces .

Specific differences

  1. Method to realize:

    • Interface: An interface is a completely abstract type that can only contain abstract methods and constant fields. The methods in the interface have no specific implementations, only method signatures. Classes use the methods defined by the interface by implementing the interface. A class can implement multiple interfaces at the same time.
    • Abstract Class: An abstract class is a semi-abstract type that can contain abstract methods and concrete methods. Abstract methods have no concrete implementation, while concrete methods can have code blocks. Classes use the methods defined by abstract classes by inheriting (extends) abstract classes.
  2. Multiple inheritance support:

    • Interfaces: Java supports classes implementing multiple interfaces, which makes interfaces very useful in multiple inheritance scenarios.
    • Abstract class: Java does not support classes inheriting multiple abstract classes. A class can only inherit one abstract class. This is because class inheritance in Java is single inheritance.
  3. Construction method:

    • Interfaces: Interfaces cannot contain constructors because interfaces cannot be instantiated directly.
    • Abstract class: An abstract class can have a constructor, and the constructor of the abstract class is called through the super keyword in the constructor of the implementation class.
  4. Field (member variable):

    • Interface: The fields in the interface are constants. They are public, static, and final by default and cannot be modified.
    • Abstract class: Abstract classes can have various fields, which can be constants, instance variables, or static fields.
  5. use:

    • Interface: Interface is mainly used to define a set of related methods, allowing different classes to implement these methods, thereby achieving polymorphism. Interfaces are often used to define contracts between classes. A class that implements an interface must provide all methods declared in the interface.
    • Abstract class: Abstract class can be used to define common properties and methods, and can provide some default implementations for subclasses. Abstract classes are often used to design base classes to provide some public behaviors without fully implementing the business logic of subclasses.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_67548292/article/details/131911134