2 回答

TA貢獻1775條經驗 獲得超8個贊
在這一行中,您聲明它sameObjectDifferentType
是一種類型Rectangle
Rectangle sameObjectDifferentType = blueRectangle;
在更真實的示例中,這將允許您擁有幾種不同的類型,您希望以相同的方式對待它們。經典的例子是CurrentAccount
, CheckingAccount
,SavingsAccount
它都繼承自Account
.
假設您的銀行應用程序具有查找?guī)舨⒄页鰩舫钟腥说拇a。該代碼將只處理抽象Account
類型。這意味著將來當您引入 a 時StudentAccount
,如果它繼承自您,則可以在您當前處理 s 的所有地方Account
使用 a ,而無需更改代碼。StudentAccount
Account
假設你有一個FilledRectangle
andWireFrameRegtangle
在你的例子中。你可以有一個calculateArea(Rectangle rect)
適用于所有矩形的方法。
但是,您為這種功能和靈活性所做的一個權衡是,當您將對象聲明為超類類型時,您將失去直接處理子類屬性的能力,因此
sameObjectDifferentType.getColor(); //Won't compile
但是,Java 確實為您提供了一種返回子類的方法,正如您通過強制轉換所指出的那樣:
((ColoredRectangle) sameObjectDifferentType).getColor(); //Will compile
作為開發(fā)人員,您知道這sameObjectDifferentType
確實是一個ColoredRectangle
幕后花絮,因此您可以安全地進行此演員陣容。但是,如果您這樣做了
((FilledRectangle) sameObjectDifferentType).getFillPattern();
你最終會得到一個運行時 ClassCastException
希望這可以幫助。

TA貢獻1865條經驗 獲得超7個贊
Rectangle sameObjectDifferentType = blueRectangle;
當你做出這樣的聲明時,你明確地告訴編譯器它應該被視為一個Rectangle
. 雖然在這種情況下它可能是一個ColoredRectangle
,但該保證消失并不需要太多。
添加回答
舉報