gpt4 book ai didi

java - 修改Java内部类中的变量

转载 作者:行者123 更新时间:2023-12-02 05:10:30 24 4
gpt4 key购买 nike

我有一个关于 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

在前一行。

为什么我无法修改内部?

谢谢!

最佳答案

不能在方法之外有语句。一种技术是使用实例初始化 block :

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
}
}
}

关于java - 修改Java内部类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17572014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com