首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试将值重新分配给类实例变量

尝试将值重新分配给类实例变量
EN

Stack Overflow用户
提问于 2014-02-27 19:57:21
回答 5查看 301关注 0票数 1

我是初学者,尝试学习java基础知识,在这个程序中,我很困惑为什么我们不能重新分配类实例变量的值。

这是程序中的错误。拜托伙计们帮我弄清楚。谢谢

代码语言:javascript
复制
class AddInsideClassVar{
    int a = 3;
    int c;
    c = a + a;
    public static void main(String args[]){
        System.out.println();
    }
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2014-02-27 20:23:19

您可以在类中定义字段,但不允许将计算语句置于方法定义之外。字段声明是形式类型的;或类型=值;

例如(从您的代码);

代码语言:javascript
复制
class AddInsideClassVar{
    static int a = 3;        // ok this is a declaration for a field (variable)
    static int c;            // ok, this is too
    //c = a + a;        // this is a statement and not a declaration. A field may be 
                      // declared only once
    static int d = a + a;    // this will work since it is part of a declaration.

    public static void main(String args[]){
        System.out.println("a=" + a + ", c=" + c + ", d=" + d);

    }
}
票数 2
EN

Stack Overflow用户

发布于 2014-02-27 20:01:30

您不能在该节中执行c=a+a。如果你需要做什么

代码语言:javascript
复制
int a = 3;
int c = a + a;  

如果使这些变量是静态的,那么可以这样做。

代码语言:javascript
复制
private static int a = 3;
private static int c;
static {
    c = a + a;
}
票数 1
EN

Stack Overflow用户

发布于 2014-02-27 20:02:34

您可以尝试这样做(只是解决办法的一个例子):

代码语言:javascript
复制
class AddInsideClassVar{
    static {
        int a = 3;
        int c;
        c = a + a;
        System.out.println(c);
    }

    public static void main(String args[]){

    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22079046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档