logo CodeStepByStep logo

inheritanceMystery3

Language/Type: Java inheritance polymorphism

Assume that the following classes have been defined:

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

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

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

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

public class Elaine extends Kramer {
    public String toString() {
        return "Elaine " + super.toString();
   }
}

public class Kramer extends Jerry {
    public void method1() {
        super.method1();
        System.out.print("Kramer 1 ");
    }

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

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

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

Jerry[] seinfeld = { new George(), new Kramer(), new Jerry(), new Elaine() };
for (int i = 0; i < seinfeld.length; i++) {
    seinfeld[i].method1();
    System.out.println();
    seinfeld[i].method2();
    System.out.println();
    System.out.println(seinfeld[i]);
    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.