简体   繁体   中英

How a program can know which method use (polymorphism)

I have two classes First class named Myclass This is the parent class

public class Myclass {
    public  static int x = 10;

     static void printX() {
         System.out.println("From the Superclass x = " + x);
    }
}

Second class named MySecondClass This the child class

public class MySecondClass extends Myclass   {
    static void printX() {
       System.out.print("From the Subclass x = " + x);
    }

    public static void main(String[] args) {
        printX();
    }
}

As a newbie in Java Programming, I want to understand the Polymorphism; How can it choose between the two methods printX() ? And in the code above why does it choose the MySecondClass method ?

Welcome to the community.

What you are trying to do here is called overriding. Although in reality java does not allow static methods to be overridden. If you instantiate the child class and call "printX" it will call the overridden method in the child class.

IE: From the Subclass x = .

But if you instantiate the parent class and call the method it will print "From the Superclass"

Although in this scenario what you are doing is not "overriding" as the methods are static. But this approach is called "method hiding"

To answer your question, it chose the second method because the second method (child class method) has hidden your super class method.

If methods are static, then it is determined at compile time which method is called, based on the class involved in the call.

If methods are instance members, then the relevant method body is looked up by its signature on the instance's concrete class, at runtime, falling back progressively upward on super classes until found. Consider that a simple map of signature-to-functionpointer, in each class and super classes, if you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM