Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 9: Inheritance
Start Practice TestPractice Test
About Exam
hard

Method Overriding and Instanceof

Mark
< Prev
Next >

Consider the following class definitions.

public class ListNode {
    public int value;
    public ListNode next;
    public ListNode(int value) { this.value = value; this.next = null; }
    public void insertAfter(ListNode node) { 
         node.next = this.next;
         this.next = node;
    }
}

public class SpecialNode extends ListNode {
    public int extra;
    public SpecialNode(int value, int extra) {
         super(value);
         this.extra = extra;
    }
    @Override
    public void insertAfter(ListNode node) {
         super.insertAfter(node);
         if(node instanceof SpecialNode) {
              ((SpecialNode)node).extra += 10;
         }
    }
    public String toString() {
         return value + "(" + extra + ")";
    }
}

public class Main {
    public static void main(String[] args) {
         SpecialNode node1 = new SpecialNode(5, 2);
         SpecialNode node2 = new SpecialNode(10, 3);
         ListNode node3 = new ListNode(15);
         node1.insertAfter(node2);
         node2.insertAfter(node3);
         System.out.println(node1.next.value);
         if(node1.next instanceof SpecialNode)
              System.out.println(((SpecialNode)node1.next).extra);
    }
}

What is printed when the main method is executed?

A

10
13

B

5
13

C

Compilation Error

D

10
3

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|