logo CodeStepByStep logo

inheritanceMystery5

Language/Type: Java inheritance polymorphism

Assume that the following classes have been defined:

public class Eve {
    public void a() {
        System.out.print("Eve a   ");
    }

    public void b() {
        System.out.print("Eve b   ");
    }

    public String toString() {
        return "Eve ts";
    }
}

public class Sam extends Eve {
    public void b() {
        a();
        System.out.print("Sam b   ");
    }

    public String toString() {
        return "Sam ts";
    }
}

public class Lucas extends Sam {
    public void a() {
        System.out.print("Lucas a   ");
        System.out.print(toString() + "   ");
    }

    public String toString() {
        String sup = super.toString();
        return sup + " " + sup;
    }
}

public class Josh extends Lucas {
    public void b() {
        System.out.print("Josh b   ");
        super.b();
    }

    public String toString() {
        return "Josh ts";
    }
}

Given the classes above, what output is produced by the following code? (Since the code loops over the elements of an array of objects, write the output produced as the loop passes over each element of the array separately.)

Eve[] elements = { new Eve(), new Sam(), new Lucas(), new Josh() };
for (int i = 0; i < elements.length; i++) {
    System.out.println(elements[i]);
    elements[i].a();
    System.out.println();
    elements[i].b();
    System.out.println();
    System.out.println();
}

element 0
element 1
element 2
element 3

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.