简体   繁体   English

从外部类访问内部类引用

[英]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. 在下面的代码中,我将head声明为内部类的引用,我试图从外部类访问它,但我无法这样做。 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: 由于head是用null初始化的,因此在创建新node您可以将null传递给next参数:

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

Why you can't access head ? 为什么您无法接触head

Because head is a member of the class node , so you first need to create an instance of that class to access it. 因为head是类node的成员,所以您首先需要创建该类的实例来访问它。

Recommendation: 建议:

As @Qadir said, use CamelCase names for classes, this is a Java convention, and helps to distinct between classes and fields. 就像@Qadir所说的,对类使用CamelCase名称,这是Java约定,有助于区分类和字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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