I'm trying to pick up Java again using the book Data Structures & Algorithms in Java, in pg 191, the book implements link list. The code first builds a link class, a link list class and a client class linkapp.
public class Link {
public int data;
public link next;
public Link (int newdata){
data=newdata;
}
}
public class Linklist {
public Link first;
public void insertFirst(int data){
Link newlink=new Link (data);
newlink.next=first;
first=newlink;
}
public boolean isEmpty(){ return (first==null); }
public void displaylist(){
if (!isEmpty()){
Link current=first;
while(current!=null){
System.out.print(current.data);
current=current.next;}
}
}
}
public class LinklistApp {
public static void main(String[] args) {
Linkedlist linkList = new Linkedlist();
linkList.insertFirst(3);
linkList.insertFirst(4);
linkList.insertFirst(5);
linkList.displaylist();
}
}
But I don't understand why the link object created locally in the insertFirst method inside linklist class can be accessed by displaylist method. Local variables will disappear when the method exits because they're just intermediate result. So how did displaylist method still have access to those link objects?