简体   繁体   中英

Accessing inner class reference from outer class

Why is that a reference to inner class can be accessed while it is declared in outer class by the outer class whereas it cannot be accessed while it is declared inside the inner class ?

In the below code I declared head as a reference inside the inner class which I tried to access from outer class but I cannot able to. If I declare the same reference in outer class it works fine. Why is that so ?

public class QueueUsingLL {
    public void additem(int n)
    {
        node nw = new node(n,head);
    if(head == null)
{
    head = nw;
}
else
{
    nw.next = head;
    head =nw;

}   
    }
public class node
{
    int item;
    node next;
    node head= null;    
    node(int item,node next)
            {
        this.item = item;
        this.next = next;

            }

}

Since head is initialized with null , at the moment of creating a new node you can pass null to the next parameter:

public void additem(int n)
{
    node nw = new node(n, null); 
}

Why you can't access head ?

Because head is a member of the class node , so you first need to create an instance of that class to access it.

Recommendation:

As @Qadir said, use CamelCase names for classes, this is a Java convention, and helps to distinct between classes and fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM