After a Java class implements an interface, does it need to implement all the methods in the interface?

1. Conclusion

    Not all classes that implement an interface must implement all methods of the interface!

2. Special circumstances

    When a Java abstract class implements an interface, it is not necessary to implement all the methods.

3. Precautions

    When a Java ordinary class implements an interface, it must implement all the methods in the interface.

4. Reason

  • Why does an abstract class not need to implement all methods?

         Because the abstract class itself is abstract, most of its methods do not need to be implemented, but only need to be declared, and other implementation processes are mostly handed over to the subclasses that inherit it. The interface itself is a more abstract form, so it is not necessary for an abstract class to implement all the methods of a more abstract interface, unless the abstract class itself needs some methods of the interface to improve itself. And other methods that are not implemented can be handed over to its derived classes to implement .

  • Why does a normal class need to implement all methods?

        All methods in a normal class need to have a method body, even an empty method. When an ordinary class implements an interface, it must implement all its methods. If any method is not implemented, data will be lost when the class is upcast to the interface (because there is no complete interface in the ordinary class at this time. data) cause the transformation to fail , which is obviously not allowed.

5. What are the benefits of using both abstract classes and interfaces?

      If an ordinary class wants to implement some methods of the interface, it needs to use the abstract class at this time. The abstract class can first implement some methods in the interface, and then the ordinary class implements the methods in the interface that it needs by inheriting the abstract class. .


Guess you like

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