Home>Article>Java> What classes in Java cannot be inherited?

What classes in Java cannot be inherited?

青灯夜游
青灯夜游 Original
2019-12-31 16:31:16 4796browse

What classes in Java cannot be inherited?

In Java, as long as a class is defined as final, or a class modified by final, it cannot be inherited.

Because the developers of jdk believe that some of the most basic classes are not necessarily open to developers. If users make mistakes when inheriting, it is likely to cause many problems. In order to prevent users from making corresponding extensions to basic classes, it also reflects the opening and closing principle in the Java design process, and these classes are ultimately designed to be final.

This is the rule of final:

When you use final for a class, a final class cannot be inherited by anyone, which means that this class cannot be inherited by anyone. An inheritance tree is a leaf class, and the design of this class has been considered to be perfect without

requiring modification or extension. For members in final classes, you can define them as final or not. As for methods, since the class they belong to is final, they naturally become final. You can also explicitly add a final to the method in the final

class, but this is obviously meaningless.

Common classes in Java that cannot be inherited are as follows:

String,

StringBuffer,

StringBuilder ,

Basic types of packaging classes such as Double, Integer, Long

, etc.

Let’s take a look at how this String class is defined:

What classes in Java cannot be inherited?

The above is how this String class is defined, we can clearly See a final modifier!

If you say that the entire class is final (prefix it with the final keyword before its definition), it means that you do not want to inherit from this class, or do not allow anyone else to take this action. In other words, for one reason or another, our class definitely does not need to make any changes; or for security reasons, we do not want to subclass (subclass processing)

Recommended learning:JavaVideoTutorial

The above is the detailed content of What classes in Java cannot be inherited?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn