有个问题可以解答么?
package untitled3;public class AAA {
public AAA() {
System.out.println("u1u");
} int v;
private static AAA a;
public static AAA method() {
if (a == null) {
a = new AAA();
return a;
}
return null;
} public int getValue() {
return v;
} public void setValue(int v1) {
if(v1!=0){
this.v = v1;}
else{
this.v=0;
}
} public static void main(String[] args) {
AAA t1 = AAA.method();
AAA t2 = AAA.method();
t2.setValue(23);
System.out.println(t1.v == t2.v);
}
}
为什么一直报错呢,谢谢
package untitled3;public class AAA {
public AAA() {
System.out.println("u1u");
} int v;
private static AAA a;
public static AAA method() {
if (a == null) {
a = new AAA();
return a;
}
return null;
} public int getValue() {
return v;
} public void setValue(int v1) {
if(v1!=0){
this.v = v1;}
else{
this.v=0;
}
} public static void main(String[] args) {
AAA t1 = AAA.method();
AAA t2 = AAA.method();
t2.setValue(23);
System.out.println(t1.v == t2.v);
}
}
为什么一直报错呢,谢谢
报下面的错java.lang.NullPointerException
at untitled3.AAA.main(AAA.java:29)
u1u
Exception in thread "main"
a = new AAA();
return a;
}
return null;
这里,你第一次AAA t1 = AAA.method();
后a就不为空了,
所以你第二次AAA.method的时候自然要返回null.
if (a == null) {
a = new AAA();
return a;
}
return null;
}
不明白为什么怎么定义啊
public static AAA method() {
if (a == null) {
a = new AAA();
return a;
}
return a;谢谢各位