Polymorphism

l          Polymorphism

 

1.  class A{

2.    int x = 1;

3.    int y = 2;

4.    int f() { return x; }

5.    static char sf() { return ‘A’; }

6.  }

7.  class B extend A{

8.    int x = 3;  // shadowing

9.    int z = 4;

10.   int f() { return x; } // overriding

11.   static char sf() { return ‘B’;} //shadowing

12.   int g(){ int x = 1;  return (x+this.x); }

13. }

14. class Z extend A{ }

15. public class SCJP {

16.   pubilc static void main(String[] args){

17.     A a = new B();

18.     B b = new B();

19.     B bb = new Z();               //error

20.     System.out.println(a.f());     // 3

21.     System.out.println(a.g());    // error

22.     System.out.println(a.z);      // error

23.     System.out.println(a.x);      // 1

24.     System.out.println(a.y);      // 2

25.     System.out.println(a.sf());    // ‘A’

26.     System.out.println(b.x);      // 3

27.     System.out.println(b.sf());    // ‘B’
28. } }

Assignment

  意思是superclassreference var可以refer to所有subclassinstance(指的是reference variable不是object,只要是subtype就可以)

  如第17行。第19行會產生compile error,因class Z不是class Bsubclass

Method Invocation

  virtual mehhod invocation,建立在method overridingpolymorphic assignment上。

  如第20行。第17行宣告一個class Areference var “a”refer to subclass B

Compile-time and Run-time Type

  compile-time typereference vartyperun-time typeobjecttype

  17行,compile-timeaA typerunt-timeaB type

  21compile err因為此時aA type,需轉型為 ((B)a).g() 才可以被執行。

Overriding and Shadowing

  instance method只能被overridden,而class methodfield只能被shadowed

  overriding instance method才有所謂的compile time typerun time type

  shadowing class method / field 永遠只有一種type,就是reference vartype

  23x和第25sf()shadowing。要看reference vartype (A)

  27行最好改為標準呼叫方式B.sf()


来自:【 Garfield 的 SCJP 閱讀筆記 】
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值