Question:
I took a quiz and got the following question:
Check the alternative corresponding to the result of executing the main method of the Java program presented below:
public class A { public void ml(){ mx(); } public static void main(String[] args){ A a = ( B) new C(); a.m1(); B b = (B) new A(); b.m1(); } public void mdx(){ System.out.print(10); } } class B extends A{ public void mx(){ System.out.print(30); } } class C extends B { public void mx(){ System.out.print(40); } }
a) The value 40 and the value 10 will be printed
b) The value 40 and the value 30 will be printed
c) The value 10 and the value 10 will be printed
d) The value 40 will be printed and the ClassCastException exception will be thrown later
e) The value 10 will be printed and the ClassCastException exception will be thrown later
Note: I saw that there is a blank space in: ( B)
The template says that the correct one is the letter D, but I have doubts about this question. Is this template correct? If yes, why? And if not, too, why?
Answer:
There are compilation errors in this code:
-
Within the
ml()
method ofA
, the invokedmx()
method does not exist in classA
. I think themdx
method was supposed to be calledmx
. -
In
main
a method calledm1
is being invoked, notml
. I think these names were supposed to be the same.
See this not working in ideone:
Main.java:4: error: cannot find symbol mx(); ^ symbol: method mx() location: class A Main.java:10: error: cannot find symbol a.m1(); ^ symbol: method m1() location: variable a of type A Main.java:12: error: cannot find symbol b.m1(); ^ symbol: method m1() location: variable b of type B 3 errors
Note: This Main.java
is because I'm compiling on ideone (and I had to take the public
out of the declaration of A
), this is just a limitation of ideone. If you are going to compile it yourself, it will show A.java
instead of Main.java
.