Contest Question: Java code about over-writing methods

Asked

Viewed 301 times

4

I took a competition and dropped the following question:

Check the alternative corresponding to the result of the execution of the main method of the Java program shown 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 shall be printed
b) The value 40 and the value 30 shall be printed
c) 10 and 10 shall be printed
d) The value 40 will be printed and the Classcastexception exception exception will be released later
e) The value 10 will be printed and the Classcastexception exception exception will be released later

Note: I saw that there is a blank in: ( B)

The feedback says that the correct one is the letter D, but I am in doubt on this question. Is this feedback correct? If yes, why? And if not, too, why?

  • 2

    If the code you posted is the same as the one in the proof none is correct.

  • 1

    This question is being discussed at the goal: http://meta.pt.stackoverflow.com/q/5743/101

  • This space in the casting for class B does not influence anything.

2 answers

14

There are compilation errors in this code:

  • Within the method ml() of A, the method mx() invoked does not exist in class A. I think it was for the method mdx be called mx.

  • In the main is being invoked a method called m1, and not ml. I think those names are supposed to be the same.

See this not working on 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: That Main.java is because I’m compiling in ideone (and I had to take the public of the declaration of A), This is just a limitation of ideone. If you compile it yourself, it will show A.java instead of Main.java.

By correcting these build errors, 40 is displayed and then one ClassCastException is launched, as is alternative D.

On the line A a = ( B) new C();, the cast is valid because although C is being instantiated, we have to C extends B, then the cast to B is valid. In addition, a reference to B can be assigned to a variable of type A because B extends A.

The fact that you have a space inside the cast is irrelevant, because the compiler tokenization process (which feeds the source code into tokens), will separate the cast into three tokens: The open-parentheses, the cast type (B) and closes it in parentheses. Spaces do not interfere with this process.

The call to a.m1() will call the method m1 of the object in the reference a. This object is that of new C(), so it’s kind of C. The class C about-writes the method m1 inherited from B and of A. Therefore, what will be executed is the method m1 class C, printing 40.

On the line B b = (B) new A();, we have that it is not true that A extends B, soon this will give a ClassCastException. The compiler allows this because the result of the subexpression new A() is the type A. A cast of A for B is allowed by the compiler because there is an inheritance relationship between these classes.

See here working on ideone. In this code, I made the suggested fixes at the beginning and added a try-catch within the main so that he can show the exception properly.

  • 3

    So it is possible to ask for the question to be challenged, right?

  • 3

    @bigown Supposing he typed it here correctly.

  • 3

    Evidently :)

2

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.