Question:
I have the following case:
Avo.java:
public class Avo {
public String quemEuSou(){
return this.getClass().getName();
}
}
Mae.java:
public class Mae extends Avo{
@Override
public String quemEuSou() {
return getClass().getName();
}
}
Filho.java:
public class Filho extends Mae{
public static void main(String[] args) {
Filho filho = new Filho();
Mae mae = (Mae)filho;
Avo avo = (Avo) mae;
System.out.println(filho.quemEuSou());
System.out.println(mae.quemEuSou());
System.out.println(avo.quemEuSou());
}
}
Result:
Son
Son
Son
Why when we cast
the class is still the one that was instantiated?
If it's still the instantiated one, how are the properties of the other classes assigned?
Example:
Filho filho2 = new Filho();
Mae mae2 = (Mae)filho2;
mae2.algumMetodoDaClasseMae();
If the class of mother2 is Filho
, where is the algumMetodoDaClasseMae()
method?
Answer:
Why when we cast the class is still the one that was instantiated?
First it is important to understand the difference between object and reference variable. When doing:
Filho filho = new Filho();
You have created a reference variable of type Filho
, this variable is called filho
. This is what was defined before the assignment operator =
.
To the right of the =
you create an object of type Filho
using the new
operator, and with the =
operator you assign it to the filho
variable.
Breaking that line into parts would look like this:
Filho filho; //cria a variável, que não referencia ninguém
filho = new Filho(); //cria o objeto e o atribui a variável filho
That is, there is only one object in your entire code, and it is of type Filho
, only you assign it to different types of reference variables, but that doesn't change the object's type.
If it's still the instantiated one, how are the properties of the other classes assigned?
Subclasses inherit the methods and attributes that are visible to them from the superclass, you can override them if desired, but not mandatory, unless they are abstract in the superclass.
If mother2's class is Child […]
Correction: The object is of type Filho
, while the reference variable is of type Mae
.
[…] where is the someMotherClassMethod() method?
As explained two items earlier, subclasses inherit the attributes and methods of the superclass. As long as they are not private.