LearnFrenzy
Sign in Take a free test

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

Error: reading a private size field from outside Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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

Main.java
class LinkedStack {
    private static class Node {
        int val;
        Node next;
        Node(int val, Node next) { this.val = val; this.next = next; }
    }

    private Node top;
    private int size;

    void push(int v) { top = new Node(v, top); size++; }
}

public class Main {
    public static void main(String[] args) {
        LinkedStack s = new LinkedStack();
        s.push(1);
        s.push(2);
        System.out.println(s.size);
    }
}
  • A Node must be public
  • B size is private to LinkedStack, a separate top-level class; add a public int size() method Correct
  • C push must return the stack
  • D LinkedStack needs a constructor
Correct Answer: Option B

javac: "size has private access in LinkedStack". (Private members of a nested class are visible to its enclosing class, which is why the study examples can read them.)

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