[英]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
所以,我哪里出問題了? 這是屏幕截圖
AA
和BB
是static
,這意味着它們屬於該類 ,而不是每個實例 。 本質上,這兩個變量在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.