请指教一段简单的java代码

来源:百度知道 编辑:UC知道 时间:2024/05/22 17:57:29
public class TestStatic {
public int a1 = 0 ;
public static int a2 = 0 ;
public static void main(String[] args) {
TestStatic t1 = new TestStatic();
TestStatic t2 = new TestStatic();
int b1 = t1.a1++ ;
int b2 = t1.a2++ ;
int b3 = t2.a1++ ;
int b4 = t2.a2++ ;
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
}
}
结果是:0 0 0 1
我觉得应该是:1 1 1 2 为什么?

还有
public class TestStatic {
public static void main(String[] args) {
int a1 = 0 ;
int a2 = 0 ;
TestStatic t1 = new TestStatic();
TestStatic t2 = new TestStatic();
int b1 = t1.a1++ ;
int b2 = t1.a2++ ;
int b3 = t2.a1++ ;
int b4 = t2.a2++ ;
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
}
}
在主方法中定义的变量不能被对象调用吗??为什么?
学的不精请多指教!!!
请回答第二个

第一段代码:
你要先理解 i++ 的意思, 他是先赋值再自增。
和++i刚好相反, 它是先自增再赋值。 理解了吧!

第二段:

你只是在main 方法中定义了 a1..TestStatic 对象t1...看不到这个变量,所以不行。

补充:
因为你实在main 方法中定义的变量类的对象是看不到的,所以调用不了,改成这样就好了:

public class TestStatic {

int a1;
int a2;

public static void main(String[] args) {
TestStatic t1 = new TestStatic ();
TestStatic t2 = new TestStatic();
int b1 = t1.a1++ ;
int b2 = t1.a2++ ;
int b3 = t2.a1++ ;
int b4 = t2.a2++ ;
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
}
}

int b1 = t1.a1++ ;
是t1.a1的值先赋给b1值后在加上去的 所以b1值是t1.a1开始赋的值
也就应该是 0
不能被调用是因为 不属于这个对象里的