First see JAVA-object-oriented-abstract classes and interfaces-primary evolution 10

First see JAVA-object-oriented-abstract classes and interfaces-primary evolution 10

Abstract class

Methods in abstract classes are abstract methods

Subclasses of an abstract class need to implement the methods of the parent class, unless the subclass is also an abstract class

Cannot new abstract class

Ordinary methods can be written in abstract classes

The abstract method must be in the abstract class

Why should there be abstract classes

Improve development efficiency and improve system scalability

interface

Ordinary class: only concrete realization

Abstract class: concrete implementation and specification (abstract method)

Interface: There are only specifications, you cannot write methods yourself

effect:

  1. constraint
  2. Define some methods and implement them for different people
  3. The interface cannot be sampled, there is no constructor in the interface
  4. implements can implement multiple methods
  5. The methods in the interface must be rewritten

the difference:

  1. The interface methods are public by default, all methods cannot be implemented in the interface (interface methods can have default implementations since Java 8), and abstract classes can have non-abstract methods.
  2. In addition to static and final variables, there can be no other variables in the interface, but not necessarily in the abstract class.
  3. A class can implement multiple interfaces, but only one abstract class can be implemented. The interface itself can extend multiple interfaces through the extends keyword.
  4. The default modifier for interface methods is public, and abstract methods can have public, protected, and default modifiers (abstract methods are just to be rewritten so they cannot be modified with the private keyword!).
  5. From a design perspective, abstraction is an abstraction of classes and a template design, while an interface is an abstraction of behavior and a norm of behavior.

Note: In JDK8, interfaces can also define static methods, which can be called directly by interface name. Implementation classes and implementations cannot be called. If two interfaces are implemented at the same time and the same default method is defined in the interface, it must be rewritten, otherwise an error will be reported

Guess you like

Origin blog.csdn.net/rr18758236029/article/details/108433487