这里编写的代码几乎相同,但是我所做的唯一更改是我替换了对象的名称。但是第一次编译成功,但是第二次编译给出错误包n不存在!
请向我解释为什么?

//FIRST PART.
//this code runs and compiles successfully!! With output-> print2

class N
{

static class M
{
void print2()
{
System.out.print("print2");
}
}

static void print()
{System.out.print("print");}


public static void main(String args[])
{
N N= new N();
N.M m = new N.M();

m.print2();
}
}




//this code has slight changes from the previous code. but fails to compile.
class N
{

static class M
{
void print2()
{
System.out.print("print2");
}

}

static void print()
{System.out.print("print");}

public static void main(String args[])
{
N n= new N();               //only this and next line are changed
n.M m = new N.M();
m.print2();
}
}

最佳答案

该行:

N.M m = new N.M();


实际上是

MyClass.InnerClass innerInstance = new MyClass.InnerClass();


这就是为什么人们通常以大写字母开头的类名和以小写字母开头的实例名的原因...

08-05 09:57