Pg188-2 覆盖 向上转型
package org.hanqi.array; public class DongWu { private String name; private String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public void run() { System.out.print("会跑"); } public void eat() { System.out.print("会吃东西"); } }
package org.hanqi.array; public class TuZi extends DongWu { public void eat() { System.out.print("会吃萝卜"); } }
package org.hanqi.array; public class TestDongWu { public static void main(String[] args) { DongWu d=new DongWu(); d.setName("动物"); d.setColor("有颜色"); System.out.print("一只"+d.getColor()+"的"+d.getName() ); d.run(); d.eat(); System.out.println(""); //子类中覆盖第二个方法 TuZi t=new TuZi(); t.setName("兔子"); t.setColor("白色"); System.out.print("一只"+t.getColor()+"的"+t.getName() ); t.run(); t.eat(); System.out.println(); //向上转型 DongWu d1=new TuZi(); d1.setName("狗"); d1.setColor("黑色"); System.out.print("一只"+d1.getColor()+"的"+d1.getName() ); d1.run(); d1.eat(); } }