第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

超類和子類的訪問限制背后的原因是什么?

超類和子類的訪問限制背后的原因是什么?

開滿天機 2022-04-28 17:03:49
我試圖了解我的代碼在 Java 中非法的最后一條語句的基本原理。請參閱下面的評論。public class Rectangle {private int height;private int width;public Rectangle(int height, int width) {    this.height = height;    this.width = width;  }}class ColoredRectangle extends Rectangle {private String color;public ColoredRectangle(int height, int width, String color) {    super(height, width);    this.color = color;}public String getColor() {    return color;}public static void main(String[] args) {    ColoredRectangle blueRectangle = new ColoredRectangle(2, 4, "blue");    Rectangle sameObjectDifferentType = blueRectangle;    ((ColoredRectangle) sameObjectDifferentType).getColor(); //Will compile    sameObjectDifferentType.getColor();  //Won't compile   }}我知道我不應該使用這種設計,而是使用不同的構造函數(shù)。我知道那getColor()是“未在 Rectangle 中定義”。盡管如此,我對這段代碼的看法是:sameObjectDifferentType 是對一個既是 Rectangle 又是 ColoredRectangle 對象的引用,因此無論我將引用聲明為 Rectangle 還是 ColoredRectangle,我都應該能夠訪問它的所有成員。那么......為什么Java是這樣設計的?
查看完整描述

2 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

在這一行中,您聲明它sameObjectDifferentType是一種類型Rectangle

Rectangle sameObjectDifferentType = blueRectangle;

在更真實的示例中,這將允許您擁有幾種不同的類型,您希望以相同的方式對待它們。經典的例子是CurrentAccountCheckingAccount,SavingsAccount它都繼承自Account.

假設您的銀行應用程序具有查找?guī)舨⒄页鰩舫钟腥说拇a。該代碼將只處理抽象Account類型。這意味著將來當您引入 a 時StudentAccount,如果它繼承自您,則可以在您當前處理 s 的所有地方Account使用 a ,而無需更改代碼。StudentAccountAccount

假設你有一個FilledRectangleandWireFrameRegtangle在你的例子中。你可以有一個calculateArea(Rectangle rect)適用于所有矩形的方法。

但是,您為這種功能和靈活性所做的一個權衡是,當您將對象聲明為超類類型時,您將失去直接處理子類屬性的能力,因此

sameObjectDifferentType.getColor();  //Won't compile

但是,Java 確實為您提供了一種返回子類的方法,正如您通過強制轉換所指出的那樣:

((ColoredRectangle) sameObjectDifferentType).getColor(); //Will compile

作為開發(fā)人員,您知道這sameObjectDifferentType確實是一個ColoredRectangle幕后花絮,因此您可以安全地進行此演員陣容。但是,如果您這樣做了

((FilledRectangle) sameObjectDifferentType).getFillPattern();

你最終會得到一個運行時 ClassCastException

希望這可以幫助。


查看完整回答
反對 回復 2022-04-28
?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

Rectangle sameObjectDifferentType = blueRectangle;

當你做出這樣的聲明時,你明確地告訴編譯器它應該被視為一個Rectangle. 雖然在這種情況下它可能是一個ColoredRectangle,但該保證消失并不需要太多。


查看完整回答
反對 回復 2022-04-28
  • 2 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號