If in class A in
public void m1()
{
mx();
}
was
public void m1()
{
mdx();
}
So the letter and would be the right answer.
But if in class A, if the mdx method, if you called it instead, mx , then the d right answer.
But the way the answer is currently typed is "Do not compile" because mx does not exist in class A. No matter if there is mx in the children, the method search is always done on the current object and on the parents, never on the children .
Here is the code for class A that would make the letter " d " be the correct one:
package testes;
public class A
{
public void m1()
{
mx();
}
public static void main(String[] args)
{
A a = ( B) new C();
a.m1();
B b = (B) new A();
b.m1();
}
public void mx()
{
System.out.print(10);
}
}
What do you learn by analyzing this exercise specifically in the section below?
A a = ( B) new C();
a.m1();
It is learned that the method that will be executed is always the one of the object in question, that is, the last one that overwritten the method, in this case it was that of the object C. If this method did not exist in the object in question, it would try to call the father's, which is B, and if there was no method in the father, would try to call the grandfather, who is A, going up the hierarchy until he found the method. Since m1 exists in C, it executes this and not the others.
Remember that the object is created when you use the word new . C was stored as a B and B was stored as an A, but in essence it remains C.
This is to allow the Polymorphism, follow an example below taken from DevMedia:
abstract class Mamífero {
public abstract double obterCotaDiariaDeLeite();
}
class Elefante extends Mamífero {
public double obterCotaDiariaDeLeite(){
return 20.0;
}
}
class Rato extends Mamifero {
public double obterCotaDiariaDeLeite() {
return 0.5;
}
}
class Aplicativo {
public static void main(String args[]){
System.out.println("Polimorfismo\n");
Mamifero mamifero1 = new Elefante();
System.out.println("Cota diaria de leite do elefante: " + mamifero1.obterCotaDiariaDeLeite());
Mamifero mamifero2 = new Rato();
System.out.println("Cota diaria de leite do rato: " + mamifero2.obterCotaDiariaDeLeite());
}
}
Reference: Article in DevMedia: Encapsulation, Polymorphism, Inheritance in Java