1

How do I declare a variable of type Node? Node is an inner class of LinkedList, and in my main method of the program I'm writing, I want to create a Node variable. But in the final line in the code snippet below I get the error message "Nose has private access in LinkedList". Why can't I use the Node type?

import java.util.LinkedList;

public class MinSplit {
    public static long leastAmount;

public static void main(String args[]) {
    LinkedList list = new LinkedList();
    LinkedList.Node node = new LinkedList.Node();
1
  • In Java we use Generics to define type of Nodes.. Commented Nov 29, 2015 at 5:41

2 Answers 2

1

Why can't I use the Node type?

Because it is declared as private. It is an internal implementation detail of the LinkedList class and you should have no reason to create instances. Clearly, this was a deliberate design decision on the part of the Java team that is intended to keep the APIs clean and avoid problems caused by people corrupting the list data structures.

If you want to instantiate the Node class so that you can perform some kind of operations on a LinkedList, think again. None of the public APIs expose the Node type in a way that would allow you to add a Node to a LinkedList ... or use it any other way. You probably need to implement your own linked list class ... from the ground up.

If you want a Node class to use for other purposes, you should declare a new class or find a suitable class in a 3rd-party library.


Actually, if you are prepared ri be nasty, it is possible to break type abstraction using reflection. It is possible to instantiate private classes, call private methods and access / update private fields. But it is a really bad idea. For a start, if Oracle decides to modify the class, your reflective hacks are liable to break.

Sign up to request clarification or add additional context in comments.

Comments

0

Node is a class which is used internally by the LinkedList class to store values of each node in the LinkedList and is defined as private class, hence you cannot reference it from outside the class.

To defined Node type for classes like LinkedList in Java we use Generics. You can define your variable like below

LinkedList<String> varName = new LinkedList<>();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.