Java static method does not have polymorphism detailed _java

Source: Internet
Author: User

The dynamic binding mechanism makes it possible for base class programming to refer to the correct subclass object, so that a reference to the base class can be directed.

However, dynamic binding can fail in the following two situations.

1, the base class method is private or final modified

This is well understood, because private explains that the method is not visible to subclasses, and that a subclass that writes a method with the same name does not duplicate the parent-class method (Override) but regenerates a new method, and there is no polymorphic problem. The same can also explain final, because the method is also not covered.

2, the method is static modification

The code looks like this.

Class Base {public
  static void Staticmethod () {
    System.out.println ("base Staticmehtod");
  }

  public void Dynamicmehtod () {
    System.out.println ("Base dynamicmehtod");
  }

Class Sub extends Base {public
  static void Staticmethod () {
    System.out.println ("Sub staticmehtod");
  } Public

  void Dynamicmehtod () {
    System.out.println ("Sub dynamicmehtod");
  }

public class TJ4 {public
  static void Main (String args[]) {
    Base c = new Sub ();
    C.staticmethod ();
    C.dynamicmehtod ();
  }
/* OutPut:
 Base staticmehtod
 Sub dynamicmehtod
 * *

The output does not output "Sub staticmehtod" as envisaged. Because a static method is associated with a class rather than an object, C.staticmethod () is equivalent to Car.staticmethod (); So try not to use instance variables to invoke static methods to avoid confusion.

The above Java static method does not have the polymorphism of the details is small to share all the content of the people, I hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.