Part 1: Short Answer Questions
Final Exam Breakdown1) What is the output of the following code:
class C {
public void method1() {
System.out.print("M1_in_C ");
}
public void method2() {
System.out.print("M2_in_C ");
}
}
class B extends C {
public String toString() {
return "B";
}
public void method2() {
System.out.print("M2_in_B ");
super.method2();
}
}
class D extends B {
public void method1() {
System.out.print("M1_in_D ");
method2();
}
}
class A extends B {
public void method2() {
System.out.print("M2_in_A ");
method1();
}
}
void main() {
C[] elements = {new A(), new B(), new C(), new D()};
for (int i = 0; i < elements.length; i++) {
elements[i].method1();
elements[i].method2();
System.out.println();
}
}BREAKDOWN:
You're given a class hierarchy with method overriding, inheritance, and a small twist: polymorphism using an array of the base type C. Each object (A, B, C, D) is stored in a C[] array, and the code loops through each one calling method1() and then method2().
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 3 more lessons in Carleton University - SYSC 2004.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- Mock exams marked by hand, with feedback
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel anytime.