as I understand it private fields can only be accessed in the class that they are defined.
I have this code for a rudimentary singly linked list:
public class LinkedList {
private class Node {
private String data;
private Node next;
private Node(String data, Node nextNode) {
this.data = data;
this.next = nextNode;
}
}
private Node head;
public LinkedList(String data) {
// Create head node, set next node null
head = new Node(data, null);
}
public void add(String data){
Node currentNode = head;
while(currentNode.next != null){
currentNode = currentNode.next;
}
currentNode.next = new Node(data, null);
}
public void printList(){
Node currentNode = head;
System.out.println(currentNode.data);
while(currentNode.next != null){
currentNode = currentNode.next;
System.out.println(currentNode.data);
}
}
}
It appears to run and work just fine, but I am trying to figure out why I can access the 'data' and 'next' fields of class Node in my functions in class LinkedList.
Adding onto this, is a nested class the same thing as a subclass defined with the 'extends' keyword?
Cheers, thanks for the help.
edit: just adding onto this question, in other implementations of linked lists I see people defining two separate classes for node, and list. It made more sense to me for node to be a nested class of linkedlist. If this is not entirely correct please let me know...
LinkedListhere if you want to compare different (but similar) implementations - there is a hierarchy of classes there with different levels of functionality (from unmodifiable lists where you can only add elements to a full implementation of a doubly linked list). I built it because thejava.util.LinkedListimplementation ofaddAll()is linear time and I needed an implementation that runs in constant time and then to extend it to support permutations (via the Steinhaus-Johnson-Trotter permutation algorithm).