我刚刚开始接触 Java。但当我读到第一章时,我有一个很大的困惑。
它说我们在创建句柄时必须“初始化”句柄,例如 String s = "asdf"
,稍后它说我们为字符串 s< 创建了一个新对象
再次,String s = new String("asdf");
。
我认为字符串s
在“初始化”中已经有一个对象(asdf),但为什么我们仍然需要重新创建它(如果我理解正确的话)?
希望有人可以向我解释这一点,在书中它只是被跳过。
最佳答案
String str1 = "asdf"; //This is a String literal
String str1 = new String("asdf"); //This is a String object
字符串对象位于堆上,而文字位于字符串文字的公共(public)池上。
不,如果你执行 String s = "asdf";
然后 String s = new String("asdf");
你会得到一个编译错误重新声明s
。
请参阅JLS欲了解更多信息。
关于java - 对创建对象感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20349558/