LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java – Find the Error · Question 2

Error: creating an inner Node class from main Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links