[英]Accessing inner class reference from outer class
为什么在外部类在外部类中声明内部类的引用时可以访问它,而在内部类内部进行声明时却不能访问它呢?
在下面的代码中,我将head声明为内部类的引用,我试图从外部类访问它,但我无法这样做。 如果我在外部类中声明相同的引用,则可以正常工作。 为什么会这样 ?
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;
}
}
由于head
是用null
初始化的,因此在创建新node
您可以将null
传递给next
参数:
public void additem(int n)
{
node nw = new node(n, null);
}
为什么您无法接触head
?
因为head
是类node
的成员,所以您首先需要创建该类的实例来访问它。
建议:
就像@Qadir所说的,对类使用CamelCase名称,这是Java约定,有助于区分类和字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.