java也是通过对象引用来操作,对于对象的作用域,假如是通过new创建的,应该是在堆里进行存储分配的,而且会一直存在
public class hello {
public static void main(String[] args){
String a = "hello";
{
String b = "world";
System.out.println(b);
}
{
String c = new String("fine");
}
System.out.println(a);
// System.out.println(b);
System.out.println(c);
}
}
a,b肯定是可以打印的,但是试了下,c打印编译是报错的,肯定是作用域存在问题
再仔细理解了一遍,这里new创建的对象虽然依然存在,但是这里关键是引用c的作用域只在{}之间,也就是根源是引用c的作用域结束了,尽管c指向的对象file依旧是存在的,而因为其唯一的引用超出了作用范围,所以已经无法访问这个对象了,因此无法打印
稍作修改,将创建引用放到{}外面,就搞定
public class hello {
public static void main(String[] args){
String a = "hello";
String b;
{
b = "world";
// System.out.println(b);
}
String c;
{
c = new String("fine");
}
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}