java - Accessing private instances in child class -


i've seen answers questions related mine on stack overflow, still left ambiguity. parent class method has access own private instance variables. if child class inherits class, happens when geta() method called on instance of child class? return a parent class or a child class?

class parent {     private int = 10;       public int geta() {        return a;     }  }  class child extends parent {     private int = 22;                }  public class test {     public static void main(string []args) throws exception {                child c = new child();         system.out.println(c.geta());    }     } 

as method geta() inherited, if call method, you'll invoke parent's method.

the current object treated parent , not child, , parent's returned.

even though have own variable a, variable wont override parent's a. different each other, have different addresses , different values.

if want geta() return child's a, need override method return new variable.

class child extends parent {     private int = 22;      @override     public int geta(){         return a;     }  } 

you "go crazy" , stuff following:

class child extends parent {     private int = 22;             @override     public int geta(){         int supera = super.geta();          return a+supera;         }  } 

that way return sum of parent's , child's a.

(just example)


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -