简体   繁体   中英

java method override in subclass applied to superclass

say i'm writing a program, and have a method in a parent class:

    public class NumbersTest {

    /**
     * @param args the command line arguments
     */

    private int number = 1;

    private static NumbersTest mNumbersTest = null;

    public NumbersTest() {
    }



    public static NumbersTest getApplication(){
       if(mNumbersTest == null)
           return new NumbersTest();
       return mNumbersTest;
    }

    public  int getNumber(){
        return number;
    }

    public static void main(String[] args) {
        int print = getApplication().calcNumber();
        System.out.println(print);
    }

    public int calcNumber(){
        int num = getNumber();

        return num + num;       
    }

}

and a child class:

public class NumbersTestChild extends NumbersTest{

    @Override
    public int getNumber(){
        return 2;
    }

    public static void main(String[] args) {
        int print = getApplication().calcNumber();
        System.out.println(print);
    }

}

when i run the parent class, i want the main() function to print 2. but when i run the child class i want the main() function to print 4, because i have overridden the getNumber() method to return a value of 2. however, the result is the same as the parent class' main() : 2.

why doesn't the overidden version of getNumber() from the child class get used instead of the regular getNumber() method in the parent class?

why doesn't the overidden version of getNumber() from the child class get used instead of the regular getNumber() method in the parent class?

You never create an instance of the child class NumbersTestChild in the code you posted, only an instance of the parent class ( getApplication() returns an instance of the parent class - NumbersTest ). Therefore the parent method is executed.

This line int print = getApplication().calcNumber() didn't create an instance of the child class. That means getNumber() basically still belongs to NumbersTest .

Something like this can work:

NumbersTestChild child = new NumbersTestChild();
int print = child.calcNumber();
.....

If you want to get desired output, change main() method code in NumbersTestChild as below.

public static void main(String[] args) {
    NumbersTest ns = new NumbersTestChild(); // Child has been created
    /* calcNumber returns 4 ( 2+2) since getNumber() returns 2 from child class */
    int print = ns.calcNumber(); 
    System.out.println(print);
}

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