ITPub博客

首页 > 应用开发 > Java > JAVA多态特性的实验

JAVA多态特性的实验

原创 Java 作者:壹頁書 时间:2013-12-19 11:29:31 0 删除 编辑
1.对象的数据成员没有多态特性

以下实验证明了数据成员不存在多态的特性。
如果是Base指针,就指向Base的数据成员;
如果是Derived的指针,就指向Derived的数据成员。
  1. class Base {
  2.     protected int i = 47;
  3. }

  4. class Derived extends Base {
  5.     protected int i = 27;
  6. }

  7. public class Test {
  8.     public static void main(String[] args) {
  9.         Base b = new Derived();
  10.         System.out.println(b.i);

  11.         Derived d = new Derived();
  12.         System.out.println(d.i);
  13.         
  14.         //运行结果:
  15.         //47
  16.         //27
  17.     }
  18. }
下面的例子也说明了同样的问题

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return i;
  5.     }

  6. }

  7. class Derived extends Base {
  8.     int i = 27;

  9.     int g() {
  10.         return i;
  11.     }
  12. }

  13. public class Test {
  14.     public static void main(String[] args) {
  15.         Derived d = new Derived();
  16.         System.out.println(d.f());
  17.         System.out.println(d.g());
  18.         //运行结果:
  19.         //47
            //27
  20.     }
  21. }
2.只有成员函数存在多态特性

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return g();
  5.     }

  6.     int g() {
  7.         return i;
  8.     }

  9. }

  10. class Derived extends Base {
  11.     int i = 27;

  12.     int g() {
  13.         return i;
  14.     }
  15. }

  16. public class Test {
  17.     public static void main(String[] args) {
  18.         Derived d = new Derived();
  19.         System.out.println(d.f());    
  20.         //运行结果:27
  1.     }
  2. }
对象d调用f方法,多态特性导致f调用子类的g方法,而不是父类的g方法,故返回27。

3.private final方法会影响多态
    Java的多态特性依赖于晚绑定(动态、运行时绑定)
    并且Java中所有的绑定都是晚绑定
    除了final方法和private方法(private是final的一种)
    这两种方法采用早绑定,即编译期就确定了运行的方法。

  1. class Base {
  2.     int i = 47;

  3.     int f() {
  4.         return g();
  5.     }

  6.     private int g() {
  7.         return i;
  8.     }

  9. }

  10. class Derived extends Base {
  11.     int i = 27;

  12.     int g() {
  13.         return i;
  14.     }
  15. }

  16. public class Test {
  17.     public static void main(String[] args) {
  18.         Derived d = new Derived();
  19.         System.out.println(d.f());
  20.         //运行结果:47
  21.     }
  22. }
    因为f函数调用的g函数是私有的,java采用早绑定,所以没有多态特性,直接绑定在了Base的g函数上。



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1063748/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339882