Abstract Methods and Abstract Classes & Interfaces

abstract method

A method modified with abstract has no method body, only a declaration. What is defined is a "specification" that tells subclasses that they must provide concrete implementations for abstract methods.

abstract class

A class that contains abstract methods is an abstract class. The specification is defined by the abstract method, and then subclasses are required to define the concrete implementation. Through abstract classes, we can strictly limit the design of subclasses and make them more common among subclasses.

The use of abstract classes

  1. Classes with abstract methods can only be defined as abstract classes

  2. An abstract class cannot be instantiated, that is, an abstract class cannot be instantiated with new.

  3. Abstract classes can contain properties, methods, and constructors. But the constructor cannot be used to new instance, it can only be used to be called by subclasses.

  4. Abstract classes can only be used to be inherited.

  5. Abstract methods must be implemented by subclasses.

Separating method design from implementation

interface

An interface is an "abstract class" that is more "abstract" than an "abstract class", and can constrain subclasses in a more standardized manner. Only constants and abstract methods.

Interface definition

  1. Access modifier: can only be public or default.
  2. Interface name: Use the same naming scheme as class name.
  3. extends: Interfaces can inherit multiple times.
  4. Constants: Properties in interfaces can only be constants, always: public static final modification. Not even writing.
  5. Methods: Methods in an interface can only be: public abstract. If omitted, it is also public abstract

Guess you like

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