繁体   English   中英

与Java对象的混淆

[英]Confusion with java objects

我是Java的初学者,目前正在使用Netbeans IDE,在这里有些困惑。 我写下了以下代码:

public class Try {

    public static int AA;
    public static int BB;

    Try(int a, int b)
    {
        AA=a;
        BB=b;
    }

    int calculate()
    {
        int c;
        c=Try.AA + Try.BB;
        System.out.println(c);
        return 0;
    }

    public static void main(String[] args) {
        Try a = new Try(1,2);
        Try b = new Try(2,3);
        a.calculate();
        b.calculate();
        // TODO code application logic here
    }
}

好吧,只是一个简单的程序,将两个整数相加,结果是:

5
5

我期待它会

3
5

所以,我哪里出问题了? 这是屏幕截图

AABBstatic ,这意味着它们属于该类 ,而不是每个实例 本质上,这两个变量在Try所有实例之间共享。 当实例化第二个Try对象时,原始的两个值被覆盖。

使两个变量为非静态将导致您期望的计算。

AA和BB属性在所有对象之间共享(并且已被重写)。

package pkgtry;

/**
 *
 * @author HeiLee
 * 
 */
public class Try {

 /* there is the mistake,

    public static int AA; 
    public static int BB;

    This attributes are shared between all objects.
*/
    public int AA; 
    public int BB;

     Try(int a, int b)
    {
        AA=a;
        BB=b;
    }
     int calculate()
    {
        int c;
        c=AA + BB;
        System.out.println(c);
        return 0;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Try a = new Try(1,2);
        Try b = new Try(2,3);
        a.calculate();
        b.calculate();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM