疑问:‘Classname instancename=value’与先new再赋值的写法是否等价?
Hey there! Great question—this is such a common point of confusion when you're just starting out with object-oriented languages like Java, so no need to apologize for asking it 😊
Let's break down the difference between your two code snippets clearly:
First, here's your code formatted properly:
// 写法1 TestClass p = new TestClass(); p = value; // 写法2 TestClass p = value;
核心区别
These two approaches are not equivalent—the reason you thought they had the same effect is likely because you never used the initial object created with new TestClass(). Let's break down what each does:
写法1: You first create a brand new
TestClassinstance, store its reference in the variablep, then immediately overwritepto point tovalueinstead. This means the originalTestClassobject you created is now "unreachable" (no variables point to it), so Java's garbage collector will eventually delete it. This is a waste of memory and completely unnecessary—you're creating an object just to throw it away.写法2: You directly assign the reference of
value(which is already aTestClassinstance) top. No extra object is created, and this is the efficient, correct way to reuse an existing instance.
什么时候需要用new Classname()?
Only when you need to create a fresh, independent instance of the class. If value is already a valid TestClass object that you want to reference with p, skip the new entirely—there's no problem with that.
For example:
// 创建一个新的TestClass实例并赋值给value TestClass value = new TestClass(); // 正确做法:通过赋值引用复用已有的实例 TestClass p = value; // 冗余写法:创建了一个立刻被丢弃的无用对象 TestClass p = new TestClass(); p = value;
总结
你的第二种写法(TestClass p = value;)不仅完全安全,反而是更优的实践——它避免了不必要的对象创建。你测试时觉得效果一致,是因为那个被丢弃的对象没有影响程序的可见行为,但在底层,第一种写法是低效的。
内容的提问来源于stack exchange,提问作者user9630194

