Java static methods do not have polymorphism, and java static methods do not.

Source: Internet
Author: User

Java static methods do not have polymorphism, and java static methods do not.

The dynamic binding mechanism enables the reference of the base class to point to the correct subclass object, making it possible to program the surface to the base class.

However, dynamic binding fails in the following two cases.

1. The base class method is private or final modified.

This is easy to understand, because private indicates that this method is invisible to the subclass. Writing a method with the same name in the subclass does not Override the parent class method ), instead, a new method is regenerated, so there is no polymorphism problem. Similarly, it can be explained that final, because the methods are not covered.

 

2. The method is static.

The Code is as follows.

 1 class Base { 2     public static void staticMethod() { 3         System.out.println("Base staticMehtod"); 4     } 5  6     public void dynamicMehtod() { 7         System.out.println("Base dynamicMehtod"); 8     } 9 }10 11 class Sub extends Base {12     public static void staticMethod() {13         System.out.println("Sub staticMehtod");14     }15 16     public void dynamicMehtod() {17         System.out.println("Sub dynamicMehtod");18     }19 }20 21 public class TJ4 {22     public static void main(String args[]) {23         Base c = new Sub();24         c.staticMethod();25         c.dynamicMehtod();26     }27 }/* OutPut:28   Base staticMehtod29   Sub dynamicMehtod30   */

 

The output result does not output "Sub staticmehtodd" as imagined ". Because the static method is associated with a class rather than an object, c. staticMethod (); equivalent to Car. staticMethod (); Do not use instance variables to call static methods to avoid confusion.

 

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.