There is the object and there is the variable. There are types that are by value and types that are by reference. In the types by value the object is placed at the location of the variable, and the types by reference they are in another location (typically the heap) and in the variable goes the reference to this object.
When you create an instance of a class, therefore you create an object, of a type, through the class constructor and the new
, you are allocating space in memory for the class object being created and initiating the values of that object. This is what you will have in memory, an object of the class indicated in the constructor. So that’s where the fields go (does not call attribute, I regret that almost everyone learns wrong) class Funcionario
, which are the fields of the classes that he inherits most the fields declared in the class itself.
The fact of declaring variable as a more general type does not change the layout memory class sense instantiated, everything is there. Only the reference to the object considers that the type is more general, in the case Pessoa
, but the object is integral.
Compiler does not let you access class-exclusive fields Funcionario
by the variable funcionario
Because they say she’s a guy who doesn’t have those camps, even if they’re actually there. Nothing prevents you to access the fields of this same object through another variable that is of the most specialized type, making a cast.
Another common mistake is to make this inheritance. The bulk of the problems that people commit in object orientation is with artificial examples or that have always been taught wrong. That is why it is necessary to be questioning and understand why it is so and not just accept that someone said it is so. See more on Official can be the role of Natural Person?.
There are other problems in this code, but it is not the focus of the question.
In this case, the instance is of the Employee class, but since the variable type is Person, you cannot access the salary attribute?
– B612
You can only access the attributes and methods that in this case are defined in the Super Class - which in this case is Person. Test the cast and check. The salary attribute will not be accessible for the Person variable.
– Gabriel Santana
I did the test and I saw that this is the case. I’m not sure I understood the part "If you need this value. You should instantiate an object from the Employee class and not the Person class.". The function object is no longer an instance of the Employee class?
– B612
You are correct. I got confused. You must use a variable of type Funcio. The instance is already of Type Funcio.
– Gabriel Santana