Question 2
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
public class Main {
class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
System.out.println(head.val + head.next.val);
}
}
- A Node needs a no-argument constructor
- B Node is a non-static inner class, so it needs an enclosing Main instance; declare it static class Node Correct
- C next must be initialised to null explicitly
- D A class cannot refer to its own type in a field
Correct Answer: Option B
javac: "non-static variable this cannot be referenced from a static context". Node classes almost never need the outer object – make them static.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!