java method override in subclass applied to superclass -


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

    public class numberstest {      /**      * @param args 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 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 run parent class, want main() function print 2. when run child class want main() function print 4, because have overridden getnumber() method return value of 2. however, result same parent class' main() : 2.

why doesn't overidden version of getnumber() child class used instead of regular getnumber() method in parent class?

why doesn't overidden version of getnumber() child class used instead of regular getnumber() method in parent class?

you never create instance of child class numberstestchild in code posted, instance of parent class (getapplication() returns instance of parent class - numberstest). therefore parent method executed.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -