logo CodeStepByStep logo

inheritanceMystery4

Language/Type: Java inheritance polymorphism

Assume that the following classes have been defined:

public class Poe extends Kylo {
    public void method2() {
        super.method2();
        System.out.print("Poe 2   ");
    }

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

public class Kylo extends Finn {
    public void method1() {
        System.out.print("Kylo 1   ");
    }

    public String toString() {
        return "Kylo";
    }
}

public class Finn extends Rey {
    public void method2() {
        System.out.print("Finn 2   ");
        method1();
    }
}

public class Rey {
    public String toString() {
        return "Rey";
    }

    public void method1() {
        System.out.print("Rey 1   ");
    }

    public void method2() {
        System.out.print("Rey 2   ");
    }
}

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.)

Rey[] elements = { new Finn(), new Rey(), new Poe(), new Kylo() };
for (int i = 0; i < elements.length; i++) {
    System.out.println(elements[i]);
    elements[i].method1();
    System.out.println();
    elements[i].method2();
    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.