Where are the private attributes of a super class stored?

3

according to the following code:

public class Ex1{
   protected int a;
   private int b;

   public Ex1(int a, int b){
     this.a=a;
     this.b=b;
   }
}

public class Ex2 extends Ex1{

   public Ex2(){
      super(4,2); //ejemplo
   }
}

public class Tester{
   public static void main (String [] args){
      Ex1 test= new Ex2();
   }
}

At the time of creation of the object referenced by the variable test. What happens to the private instance attribute "b" of class Ex1? I understand that the object will be created of type Ex2, and within its internal state will be its private attributes (if any) and those it inherits. But I'm not sure where the value of "b" would be saved. I did it in the compiler a while ago, and it does save, because if I create a getB method in Ex1, I can get its value.

    
asked by Miruuu 24.12.2017 в 22:13
source

1 answer

1

First let's take a look at the Javadoc , specifically in the section < Strong> Private members in a Superclass :

  

A subclass does not inherit the private members of its parent class . However, if the parent class has public or protected methods to access its private attributes, these can be used in the daughter class.

(Translated and highlighted by me)

This phrase is quite enlightening: The daughter class does not contain the attributes of the parent class . In fact, the methods to access them are not even yours, you have to use the ones provided by the parent class. Consider the example:

public class Ex1 {
    private int numero = 1;

    public int getNumero() {
        return numero;
    }
}

public class Ex2 extends Ex1 { }  // podemos llamar a getNumero

public class Ex3 extends Ex1{
    @Override                     // ahora getNumero pertenece a Ex3
    public int getNumero() {
        return numero;            // error! Hay que usar super.getNumero()
    }
}

Think of it as if the parent class had its private attributes separately, and if the daughter wants to access them, she has to request it using the methods that the parent class has available . . p>

Internally, at the moment of instantiation, Java allocates memory for all the instance variables of the instantiated class and all the superior ones, and the methods that access those variables are limited according to the access rules.

    
answered by 26.12.2017 / 09:41
source