Java study notes (7)--The similarities and differences between abstract classes and interfaces

1. What is an abstract class

       Abstract classes are higher-level abstractions. Both abstract classes and abstract methods need to be modified with the abstract keyword. The methods in the class are used to describe the behavior of the class, but sometimes we can only determine the exact description method during runtime. When you need to use abstract classes. A class with abstract methods can only be defined as abstract classes, and abstract classes can have no abstract methods.

       The rules for abstract methods and abstract classes are as follows:

  • Abstract classes and abstract methods must be modified with the abstract keyword, and abstract methods cannot have method bodies
  • Abstract classes cannot be instantiated. Can only be used for inheritance
  • The constructor of an abstract class is not used to instantiate, but is called by subclasses to initialize the abstract class
  • Classes with abstract methods can only be defined as abstract classes

2. What is an interface

      An interface is a specification that specifies which services must be provided to the outside world

Third, the two similarities

  • Neither interfaces nor abstract classes can be instantiated
  • Both interfaces and abstract classes can contain abstract methods. Subclasses that implement interfaces or inherit abstract classes must implement abstract methods.

Fourth, the difference between the two

  • An interface is a specification that specifies what services the implementer must provide to the outside world
  • The interface cannot be changed frequently, otherwise it will affect the whole system
  • An interface can only contain abstract methods and default methods, while an abstract class can contain ordinary methods
  • Static methods cannot be defined in interfaces, but static methods can be defined in abstract classes
  • Only static constants can be defined in the interface, and ordinary member variables cannot be defined. In the abstract class, static constants and ordinary member variables can be defined.
  • An interface cannot contain a constructor, an abstract class contains a constructor, the constructor does not instantiate the abstract class, but lets subclasses call the constructor to complete the initialization of the abstract class
  • An interface cannot contain an initializer block, an abstract class can contain an initializer block
  • A class can only have one direct parent class, but can implement multiple interfaces

V. Summary

      An interface is a specification, and an abstract class is a higher-level abstraction. Abstract classes can include common class implementations, but interfaces cannot include common class implementations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936482&siteId=291194637
Recommended