java - What happens when base and derived classes each have variables with the same name -


consider int a variables in these classes:

class foo {     public int = 3;     public void addfive() { += 5; system.out.print("f "); } } class bar extends foo {     public int = 8;     public void addfive() { this.a += 5; system.out.print("b " ); } } public class test {     public static void main(string [] args){         foo f = new bar();         f.addfive();         system.out.println(f.a);     } } 

i understand method addfive() have been overridden in child class, , in class test when base class reference referring child class used call overridden method, child class version of addfive called.

but public instance variable a? happens when both base class , derived class have same variable?

the output of above program

b 3  

how happen?

there 2 distinct public instance variables called a.

  • a foo object has foo.a variable.
  • a bar object has both foo.a , bar.a variables.

when run this:

    foo f = new bar();     f.addfive();     system.out.println(f.a); 

the addfive method updating bar.a variable, , reading foo.a variable. read bar.a variable, need this:

    system.out.println(((bar) f).a); 

the technical term happening here "hiding". refer jls section 8.3, , section 8.3.3.2 example.

note hiding applies static methods same signature.

however instance methods same signature "overridden" not "hidden", , cannot access version of method overridden outside. (within class overrides method, overridden method can called using super. however, that's situation allowed. reason accessing overridden methods forbidden break data abstraction.)


the recommended way avoid confusion of (accidental) hiding declare instance variables private , access them via getter , setter methods. there lots of other reasons using getters , setters too.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -