2016-08-15 84 views
0

我是java的初学者,我正在使用Netbeans IDE,我在这里有一些困惑。 我写下如下代码:与java对象混淆

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 

那么,我哪里错了?

+3

请勿使实例变量static,即'public int AA;'而不是'public static int AA;'等等(并且看看命名约定以及如何使用访问修饰符如public '正确 - 这与您的问题没有直接关系,但您也应该了解这一点)。 – Thomas

+0

非常感谢!我纠正了我的代码,我将看看命名约定。我想我需要买一本适当的书。 – Hei

回答

3

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

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

+0

非常感谢!现在事情运作良好! – Hei

1

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(); 
    } 

} 
+0

只要您不将'c = Try.AA + Try.BB'行更改为'c = this.AA + this.BB',就不会工作。另外,对于实例变量,“AA”和“BB”是可怕的名字。 – Clashsoft

+0

@Clashsoft你说得对,对不起。 –

+0

谢谢!而且,这些名字是可怕的。 – Hei