亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何在java中通過接口對象訪問派生的類成員變量?

如何在java中通過接口對象訪問派生的類成員變量?

qq_花開花謝_0 2022-09-01 18:07:04
我是一名新的Java程序員。我有以下類的層次結構:public interface basepublic interface Object1Type extends basepublic interface Object2Type extends Object1Typepublic class Object3Type implements Object2Type{       byte[] value;} 我有另一個類,我有一個Object1Type a的對象;我可以使用此對象a訪問Object3Type類型的byte[]值成員嗎?
查看完整描述

1 回答

?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

您可以使用類強制轉換:


public static void main(String args[]) {

    Object1Type a = new Object3Type();


    if (a instanceof Object3Type) {

        Object3Type b = (Object3Type) a;

        byte[] bytes = b.value;

    }

}

但這是危險的,不推薦的做法。演員正確性的責任在于程序員。請參閱示例:


class Object3Type implements Object2Type {

    byte[] value;

}


class Object4Type implements Object2Type {

    byte[] value;

}


class DemoApplication {


    public static void main(String args[]) {

        Object1Type a = new Object3Type();


        Object3Type b = (Object3Type) a; // Compiles and works without exceptions

        Object4Type c = (Object4Type) a; // java.lang.ClassCastException: Object3Type cannot be cast to Object4Type

    }

}

如果這樣做,請至少使用前面的 instanceof 運算符檢查對象。


我建議您在其中一個接口(現有或新)中聲明一些 getter,并在類中實現此方法:


interface Object1Type extends Base {

    byte[] getValue();

}


interface Object2Type extends Object1Type {}


class Object3Type implements Object2Type {

    byte[] value;


    public byte[] getValue() {

        return value;

    }

}


class DemoApplication {


    public static void main(String args[]) {

        Object1Type a = new Object3Type();

        byte[] bytes = a.getValue();

    }

}


查看完整回答
反對 回復 2022-09-01
  • 1 回答
  • 0 關注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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