天天看點

java new 的作用域,java引用和對象作用域

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);

}

}