method overriding Vs class variable overriding in java -


i trying sample code checking class variable overriding behavior in java. below code:

class a{   int i=0;    void sayhi(){     system.out.println("hi a");   } }   class b extends a{   int i=2;    void sayhi(){     system.out.println("hi b");   } }   public class helloworld {  public static void main(string[] args) {     a= new b();     system.out.println("i->"+a.i); // prints 0,     system.out.println("i->"+((b)a).i); // prints 2, b     a.sayhi(); //  method b gets called since object of type b   } } 

i not able understand whats happening @ these 2 lines below

system.out.println("i->"+a.i); // prints 0, system.out.println("i->"+((b)a).i); // prints 2, b 

why a.i print 0 if object of type b? , why print 2 after casting b?

i not method - it's data member. data members don't override, hide. though instance b, has 2 data members - i a , i b. when reference through a reference former , when use b reference (e.g., explicitly casting it), you'll latter.

instance methods, on other hand, behave differently. regardless of the type of reference, since instance b instance, you'll polymorphic behavior , string "hi b" printed.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -