Java中對域和靜態方法的訪問不具有多態性

來源:互聯網
上載者:User

標籤:自己   包含   system   rgs   method   ret   程式   綁定   log   

1.將方法調用同方法主體關聯起來被稱為

2.編譯期綁定(靜態)是在程式編譯階段就確定了引用對象的類型

3.運行期綁定(動態綁定)是指在執行期間判斷所引用對象的實際類型,根據其實際的類型調用其相應的方法

4.除了static方法和final方法(private方法屬於final方法),其他所有方法都是後期綁定,Java中所有的方法都是通過動態綁定來實現多態

5.訪問某個域的行為不具有多態性

package polymorphism;class SuperField {public int field = 1;public int getField() {return field;}}class SubField extends SuperField {public int field = 2;public int getField() {return field;}public int getSuperField() {return super.field;}}public class FieldPolymorphism {public static void main(String[] args) {SuperField sup = new SubField();System.out.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField());SubField sub = new SubField();System.out.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() +", sub.getSuperField() = " + sub.getSuperField());}}

 輸出結果:

sup.field = 1, sup.getField() = 2
sub.field = 2, sub.getField() = 2, sub.getSuperField() = 1

 

當SubField對象轉型為Super引用時,任何域訪問操作都將由編譯器解析,因此不是多態的,SubField實際包含兩個稱為field的域:自己的和從SuperField處繼承來的

通常將網域設定成private,不能直接存取,也不能被繼承,通過調用方法來訪問

6.訪問某個靜態方法不具有多態性,不與單個對象相關聯

package polymorphism;class Super {public static String staticMethod() {return "Super staticMethod()";}}class Sub extends Super {public static String staticMethod() {return "Sub staticMethod()";}}public class StaticPolymorphism {public static void main(String[] args) {Super sup = new Sub();System.out.println(sup.staticMethod());System.out.println(Sub.staticMethod());}}

 輸出結果:

Super staticMethod()
Sub staticMethod()

 

Java中對域和靜態方法的訪問不具有多態性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.