Two Special Cases about Java Polymorphism

Source: Internet
Author: User

The two situations I want to analyze are related to static and final modifiers ~

1) static

Static modification methods cannot be overwritten, and final modification methods cannot be overwritten.

2) Final

Because the visibility of private and public is different, private is only visible to a specific class, but not to subclass. Therefore, both the subclass and parent classes can use the same method of private final modification, public final void Test2 (){};

The public subclass shows that if both the subclass and the parent class have public final, there are two identical public final methods in the subclass. This is obviously not feasible. Therefore, subclass and parent classes are not allowed to use the same public final modifier method (the same is true for protected and for non-access modifiers ).

Example: (cause and result)

Package COM. xujin; class base {private final void test () {system. out. println ("base, test");} public final void Test2 () {system. out. println ("base, Test2");} public static void test3 () {system. out. println ("base, test3") ;}} public class test extends base {// allow both subclass and parent classes to have private final, however, public final is not allowed to exist. Private final void test () {system. out. println ("Test, test");} // public final void Test2 () {}// cannot override the final method/static is not overwritten public static void test3 () {system. out. println ("Test, test");} public static void main (string... AGRs) {base A = new test (); Base B = new test (); //. test (); // The method test () from the type base is not visible. test2 (); // base, Test2. test3 (); // base, test3 B. test2 (); // base, Test2 B. test3 (); // base, test3 }}

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.