basic java code to understand inheritance -


why system.out.println(b.h + " " + b.geth()); prints following:

beta 44 <br/> 4 44          (notice in second line) 

i expecting print this:

4 beta 44 44   (this 1 in 1 line) 

the reason why thought print way because call b.h first 4.then call b.geth() print beta 44 44

here code:

class baap{          int h = 4;         public int geth(){                 system.out.println("beta " + h);                 return h;         } }  class beta extends baap{         int h = 44;         public int geth(){                 system.out.println("beta " + h);                 return h;         }          public static void main (string [] args) {                 baap b = new beta();                 system.out.println(b.h + " " + b.geth());         }  } 

first, call geth() prints "beta 44", since argument of system.out.println(b.h + " " + b.geth()) evaluated before println called.

then system.out.println(b.h + " " + b.geth()) prints "4 44".

b.h returns 4 because there no overriding instance variables, , since b's compile time type baap, b.h returns instance variable of super class.

b.geth() returns 44 because b's runtime type beta, overrides geth().


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -