class Outer
{
int x=3;
void method()
{
class Inner
{
void function()
{
System.out.println(Outer.this.x);
}
}
new Inner().function();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method();
}
}
上面的程序可以运行,结果为 3
但是我把上面的改一下,注意,改的地方我会提醒。
1 class Outer
{
int x=3;
void method()
{
new Inner().function();\\我把它提上来后为什么不能运行。
class Inner
{
void function()
{
System.out.println(Outer.this.x);
}
}
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method();
}
}
我继续改一下,下面的为什么不能运行了?
class Outer
{
int x=3;
void method()
{
class Inner
{
static void function()//我在此处改成了 static ,为什么不能加static。
//不要说在类class前加static,一样的不行。
{
System.out.println(Outer.this.x);
}
}
new Inner().function();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method();
}
}
我继续改一下。
class Outer
{
int x=3;
void method()
{
int y=4 //此处改了
class Inner
{
void function()
{
System.out.println(y);//此处改了,为什么它没有访问成功了?为什么不不能直接调用Y?
}
}
new Inner().function();
}
}
继续改
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method();
}
}
我继续改一下
class Outer
{
int x=3;
void method(final int a )//此处a是final,为什么可以把它当变量继续使用。7如何传它。
{
final int y=5
class Inner
{
void function()
{
System.out.println(Outer.this.x);
}
}
new Inner().function();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method(7);
}
}
我继续改一下
class Outer
{
int x=3;
void method(final int a )
{
final int y=5
class Inner
{
void function()
{
System.out.println(Outer.this.x);
}
}
new Inner().function();
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
new Outer().method(7);//此处7已经被锁住了,为什么还是可以传8进去?
new Outer().method(8);
}
}
上面的一些问题都是很有针对性,如果大家能够好好的想明白,我想对你的java基础还是很有帮值得。
这是传智播客的老师经典的解释:
内部类定义在局部时:
1 不可被成员修饰符修饰(你需要考虑的是,哪里是局部位置。)
2 可以直接访问外部类的成员,因为持有外部类的引用,但是不可以访问它在局部中的变量,只能访问被final修的局部变量。