[英]Does java subclass use the same superclass field object
我目前正在學習Java。 看下面的代碼:
package classtest1;
class ClassSuper
{
public Object myObject = new Object();
public ClassSuper(){}
}
public class ClassTest1 extends ClassSuper
{
public ClassTest1()
{
System.out.println("this.myObject.equals(super.myObject) return: " + this.myObject.equals(super.myObject));
System.out.println("this.myObject == (super.myObject) return: " + this.myObject == (super.myObject));
}
public static void main(String[] args)
{
ClassTest1 myClassTest1 = new ClassTest1();
}
}
輸出如下:
run:
this.myObject.equals(super.myObject) return: true
false
BUILD SUCCESSFUL (total time: 0 seconds)
我的問題是,為什么等於和“==”不一樣? 使用“==”時為什么輸出false。 Subclass會在內存中創建一個新的副本myObject嗎?
Subclass會在內存中創建一個新的副本myObject嗎?
不。您只是不比較您認為比較的對象。
System.out.println("this.myObject == (super.myObject) return: " + this.myObject == (super.myObject));
將String
"this.myObject == (super.myObject) return: " + this.myObject
與(super.myObject)
並返回false
。
當計算傳遞給System.out.println
的參數時,將從左到右進行計算。 首先將this.myObject.toString()
連接到"this.myObject == (super.myObject) return: "
,然后將生成的String
與帶有==
運算符的(super.myObject)
進行比較。
如果用括號包裝比較:
System.out.println("this.myObject == (super.myObject) return: " + (this.myObject == super.myObject));
你將獲得你想要的比較將返回true
,因為this.myObject
和super.myObject
引用相同的Object
。
System.out.println("this.myObject == (super.myObject) return: " + this.myObject == (super.myObject));
實際上這是比較字符串。 第一個字符串是
"this.myObject == (super.myObject) return: " + this.myObject
第二個字符串是
(super.myObject)
如果要比較對象,請使用小括號作為
(this.obj == (super.obj))
您對產生的輸出感到困惑,因此下面是您需要關注的幾點。
運算符首選項 :Java具有明確定義的規則,用於指定表達式具有多個運算符時計算表達式中運算符的順序。
為了更好地理解,請檢查執行以下代碼的嘗試。
public class ClassTest1 extends ClassSuper
{
public ClassTest1()
{
System.out.println("this.myObject.equals(super.myObject) return: " + (this.myObject.equals(super.myObject)));
System.out.println("this.myObject == (super.myObject) return: " + this.myObject == (super.myObject));
System.out.println("this.myObject == (super.myObject) return: " + (this.myObject == (super.myObject)));
}
...
}
具有上述更改的程序控制台。
this.myObject.equals(super.myObject) return: true
false
this.myObject == (super.myObject) return: true
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.