FrankK
FrankK

Reputation: 511

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?

Upvotes: 1

Views: 85

Answers (3)

Ravindra babu
Ravindra babu

Reputation: 38950

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);
}

Upvotes: 0

cuongnguyen
cuongnguyen

Reputation: 96

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();
.....

Upvotes: 1

Eran
Eran

Reputation: 394136

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.

Upvotes: 2

Related Questions