[英]Modify variable in Inner class Java
我有一个Java内部类的问题,我无法弄清楚。 假设你有
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer; //(or just outer as it is not shadowed)
inner = 3; //or whatever, even outer = 3
}
}
好吧,当我写下最后一个赋值时,我得到了编译错误
Syntax error on token ";", , expected
在先例线上。
为什么我不能修改内心?
谢谢!
你不能在方法之外有声明。 一种技术是使用实例初始化块 :
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer; //(or just outer as it is not shadowed)
// instance initializer block:
{
inner = 3; //or whatever, even outer = 3
}
}
}
或者,定义构造函数:
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer; //(or just outer as it is not shadowed)
Inner() {
inner = 3; //or whatever, even outer = 3
}
}
}
您必须将代码放在方法或构造函数中:
class Outer
{
int outer = 0;
class Inner
{
int inner = Outer.this.outer;
public Inner() {
inner = 3;
}
public increment() {
inner++;
}
}
}
你对inner
赋值必须在方法或构造函数中,而不是在类中“松散”。
你需要包括这一行:
inner=3;
在内部类的方法中。
Yuo不能直接初始化inner = 3;
外部方法。确保inner = 3;
在任何方法或构造函数中。
public Inner()
{
inner = 3;
}
上述评论都不够清楚。
因此,当您声明一个类时,您要么提及(声明)变量来赋予一些值,例如private int x = 3; 它的任务也包括在课堂本身。 为什么它编译呢?
事情是在对象拳击我假设,现在没有时间,晚上我会回家并为你清除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.