What is the difference between abstract class and interface

Abstract Class: A class is abstract if it contains abstract methods. In Java, a class can be represented as an abstract class by declaring some methods in the class or class as abstract (can only modify classes or methods, not attributes).

Interface: An interface refers to a collection of methods. All methods in an interface have no method body. In Java, an interface is implemented by the keyword interface.

A class that contains an abstract method must be declared abstract, and a method declared abstract cannot contain a method body. An abstract class cannot be instantiated during use, but an object can be created to point to an instance of a concrete subclass. Subclasses of abstract classes provide concrete implementations for all abstract methods in the parent class, otherwise they are also abstract classes.
Interfaces can be thought of as variants of abstract classes. All methods in the interface are abstract, and the member variables in the interface are static final types.

Same point:

  1. can't be instantiated
  2. An implementation class of an interface or a subclass of an abstract class can only be instantiated after implementing the methods in the interface or abstract class

difference:

  1. An interface only has a definition, and its methods cannot be implemented in the interface. Only the class that implements the interface can implement the methods defined in the interface, while the abstract class can have definitions and implementations, that is, its methods can be implemented in the abstract class.
  2. Interfaces need implements, and abstract classes can only be extended. A class can implement multiple interfaces and can only inherit one abstract class. Therefore, the use of interfaces can indirectly achieve the purpose of multiple inheritance.
  3. An interface emphasizes the implementation of a specific function, has - a. Abstract classes emphasize ownership, is - a
  4. The methods in the interface can only be modified with the keyword public abstract, and the properties in the interface are public static final by default and must be initialized
  5. Interfaces are used to implement more commonly used functions, which are convenient for future maintenance or adding and deleting methods; while abstract classes are more inclined to act as public classes, and do not try and re-modify the code inside in the future.

Guess you like

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