public class Formats {
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.s1);
}
}class Test {
String s1 = "hello";
Test() {
String s1 = "world";
}
}请问输出结果是?为什么呢?多谢!
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.s1);
}
}class Test {
String s1 = "hello";
Test() {
String s1 = "world";
}
}请问输出结果是?为什么呢?多谢!
String s1 = "world";
}这个s1是局部变量System.out.println(t.s1);这个输出的是成员变量的值
t.s1是输出的成员变量的值
说的详细一点就是当用构造方法创建对象的时候Test t = new Test(),在内存的栈中存在一个变量t,它指向堆内存
一个对象,对象内有一个成员变量s1值为hello,当输出是输出的是对象的成员变量
而
Test1() {
String s1 = "world";
}在调用构造方法的时候会在栈中分配一个临时的空间为s1值为world,当构造方法调用结束之后,那个空间自动释放。
建议LZ分析一下内存
yangkaixin1226