If in class A in
public void m1()
{
mx();
}
were
public void m1()
{
mdx();
}
Then the letter and would be the right answer.
But if in class A, if the method mdx, called instead of that, mx, then the letter d would be the right answer.
But as it is currently typed the answer is "Do not compile" because mx does not exist in class A. No matter if there is mx in the children, the search for the method is always done in the current object and in the parents, never in the children.
Follow the code of class A that would make the letter "d" be the right 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 is learned 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 that of the object in question, that is, the last one that overwritten the method, in that case it was the object C. If there was no such method in the object in question, it would try to call the one of the father, which is B, and if there was no method in the father, I would try to call grandfather, who is A, up the ladder until I found the method. As there is M1 in C, it performs this and not the others.
Remember that the object is created when using the word new. C was stored as a B and B was stored as an A, but in essence remains C.
This serves to allow Polymorphism, follows 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: Devmedia Article: Encapsulation, Polymorphism, Java Heritage
If the code you posted is the same as the one in the proof none is correct.
– Henrique Luiz
This question is being discussed at the goal: http://meta.pt.stackoverflow.com/q/5743/101
– Maniero
This space in the casting for class B does not influence anything.
– Antonio Alexandre