Java

本类阅读TOP10

·使用MyEclipse开发Struts框架的Hello World!(录像1)
·hibernate配置笔记
·AOP编程入门--Java篇
·linux下Tomcat 5.0.20 与 Apache 2 安装/集成/配置
·在win2003下整合了整合Tomcat5.5+ apache_2.0.53+ mod_jk_2.0.47.dll
·构建Linux下IDE环境--Eclipse篇
·Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)
·ASP、JSP、PHP 三种技术比较
·Tomcat5.5.9的安装配置
·AWT GUI 设计笔记(二)

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Polymorphism

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

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 閱讀筆記 】


相关文章

相关软件