Method overrides in Java with the final keyword

Source: Internet
Author: User

Does the method in Java override the final keyword with the following program for errors?

Class Base {Private final void method () {System.out.println ("in Base ...");}} Class Sub extends Base {public void method () {System.out.println ("in Sub ...");}}

The answer is right.

You can declare classes, member variables, and member methods by using the final keyword, which, once declared, is non-inheritable, non-modifiable, and cannot be overwritten.

In this case, the base class method is private and is not visible in the subclass, so the method with the same name in the subclass is no longer overwritten, and is equivalent to a new method name.

This is a special case, and the book says that if a method in a subclass has the same method name and parameter signature as a method in its superclass, the method in the subclass is said to overwrite the method in the (override) superclass. This is not a strict statement.

Extra tip:

The final method cannot be overridden by a quilt class. When the compiler calls the final method, it goes into the inline mechanism (inserting the method body directly into the call), greatly improving execution efficiency (around 50%). Many methods in the API class, such as the GetClass method in the object class, are the final method. Description: Final cannot be used to modify a construction method.

Method overrides in Java with the final keyword

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.