6 域的继承:magCard >子类可以继承父类的所有非私有域 域的隐藏 子类重新定义一个与从父类那里继承来的域变量完全相 同的变量,称为域的隐藏 注意 一被隐藏的父类的域仍然存在 一被隐藏的域可以通过supe或父类的对象来引用 一当对象的一个域被访问,对象的声明类型决定是访 问父类的域还是子类的域
6-11 Programming in Java • 域的隐藏 ¾ 子类重新定义一个与从父类那里继承来的域变量完全相 同的变量,称为域的隐藏 ¾ 注意 —被隐藏的父类的域仍然存在 —被隐藏的域可以通过super或父类的对象来引用 —当对象的一个域被访问,对象的声明类型决定是访 问父类的域还是子类的域 域的继承与隐藏 • 域的继承: magCard ¾子类可以继承父类的所有非私有域
下 6 P93例5-2 Public class TestHiddenField public static void main(String args[] D200 Card my200 new D200 CardO; my200.balance 50.0; System.out.println("Supper:"+my200.getBalance();0.0 if (my200.performDial() System.out.println("Subclass:"+my200.balance); 49.5 }
6-12 Programming in Java 示例 • P93 例5-2 Public class TestHiddenField { public static void main(String args[ ] ) { D200_Card my200 = new D200_Card(); my200.balance = 50.0; System.out.println(“Supper:”+my200.getBalance()); if (my200.performDial()) System.out.println(“Subclass:”+my200.balance); } } 0.0 49.5
0%33 6 。方法的继承:lC-card 方法的覆盖 一子类重新定义与父类同名的方法 要求 ·新旧方法必须有相同方法名、参数表、返回 类型(如果只有方法名相同,测是重载) ·方法必须是non-static
6-13 Programming in Java • 方法的覆盖 —子类重新定义与父类同名的方法 —要求 • 新旧方法必须有相同方法名、参数表、返回 类型 (如果只有方法名相同,则是重载) • 方法必须是 non-static 方法的继承与覆盖 • 方法的继承 : IC-Card
6 class SuperShow public String str=“SuperStr”?; public void show({ System.out.println("Super.show:"+str);} class ExtendShow extends SuperShow public String str="ExtendStr"; public void show({ System.out.println("Extend.show"+str); public static void main(String[]args){ ExtendShow ext new ExtendShow(; SuperShow sup ext;
6-14 Programming in Java class SuperShow { public String str = “SuperStr”; public void show() { System.out.println(“Super.show:” + str); } } class ExtendShow extends SuperShow { public String str = “ExtendStr”; public void show() { System.out.println(“Extend.show” + str); } public static void main(String[] args) { ExtendShow ext = new ExtendShow(); SuperShow sup = ext; Example(1)
sup.show();//show of actual type,i.e.ExtendShow ext.show0; System.out.println("sup.str="+sup.str); System.out.println("ext.str ="+ext.str); Two kinds of reference:actual type(ext),super type(sup) Result:Extend.show:ExtendStr //actual type:Extend Extend.show:ExtendStr sup.str SuperStr /declared type:SuperShow ext.str ExtendStr//declared type:ExtendShow
6-15 Programming in Java sup.show();//show of actual type, i.e. ExtendShow ext.show(); System.out.println(“sup.str=”+sup.str); System.out.println(“ext.str =”+ext.str); } } • Two kinds of reference: actual type(ext), super type(sup) • Result: Extend.show:ExtendStr // actual type: Extend Extend.show:ExtendStr sup.str = SuperStr // declared type: SuperShow ext.str = ExtendStr// declared type: ExtendShow Example(2)