多态练习案列分析
1 package com.polymorhic; 2 //多态的练习题 3 public class exercise { 4 public static void main(String[] args) { 5 Sub s = new Sub(); 6 //编译类型为Sub,运行类型为Sub, 7 // 执行s.count:首先s是sub运行类型,所以去调用sub方法中的count属性 8 System.out.println(s.count);//20 9 //执行s.display:首先s是sub运行类型,所以去调用sub子类中的display方法 10 s.display(); 11 //把s赋值给b,b的编译类型是Base 12 Base b = s; 13 System.out.println(b==s);//true 14 //执行b.count:首先b的编译类型是Base,所以去调用Base方法中的count属性 15 System.out.println(b.count);//10 16 //执行b.display():首先b的编译类型是Base,
//运行类型是s,去调用sub方法中的display方法 17 b.display();//20 18 } 19 } 20 21 class Base{ 22 int count = 10; 23 public void display(){ 24 System.out.println(this.count); 25 } 26 } 27 28 class Sub extends Base{ 29 int count =20; 30 public void display(){ 31 System.out.println(this.count); 32 } 33 }
想多了都是问题,做多了才是答案

浙公网安备 33010602011771号