What is the final class and the final method in Java? What are their roles?

Source: Internet
Author: User

Final Class A {}, so that the defined Class A is the final class, the final class cannot be inherited, that is, the code cannot be written, class B extends a {}.

final void B () {}, the method defined is the final method, and the final method cannot be overridden in a subclass, that is, if a subclass inherits the class of the final method, then the method of void B () {} can no longer appear in this subclass.

-----------------------------------------------------------------------------

The final class may not contain the final method, and the class containing the final method can be either the final class or the non-final class.

The final class has a final decoration and can not derive subclasses.

-----------------------------------------------------------------------------

A class that is final decorated cannot be inherited, so it cannot be used as a parent class for other classes, and is typically represented by the string class. The string class only lets you use it directly.

-----------------------------------------------------------------------------

Final can modify classes, methods, and variables.

When modifying a class: it means that the decorated class is the final class, and any class can no longer inherit it.

When modifying a function: It means that the method is the final method in the class, and the method that inherits the subclass of the class cannot rewrite it.

When modifying a variable: it means that the modified variable is a constant or an end-state variable, and once initialized it is no longer possible to change the value of the variable.

What is the final class and the final method in Java? What are their roles?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.