package com_package1; public class Dog extends Animal{ public void eat() { System.out.println("啃骨头"); }//将父类中的抽象方法实例化 public void lookHome() { System.out.println("看家"); }//够的特有属性 }
package com_package1; public class Cat extends Animal { public void eat() { System.out.println("eat fish"); } public void catchMouse() { System.out.println("catMouse"); } }
package com_package1; public class Pig extends Animal{ public void eat() { System.out.println("siliao"); } public void gongDi() { System.out.println("gongdi"); } }
package com_package1; public class DuotaiDemo { public static void main(String[]args) { Pig p = new Pig(); Dog d = new Dog(); Cat c = new Cat(); method(p); method(d); method(c); } public static void method(Animal a) { a.eat(); if(a instanceof Cat) {Cat c = (Cat)a; c.catchMouse();} else if(a instanceof Dog) { Dog d = (Dog)a; d.lookHome(); } else {Pig p = (Pig)a; p.gongDi();} } }
接口和多态练习
package com_package1; public class NoteBook { public void run() { System.out.println("enable"); System.out.println("disabble"); } public void useUSB(USB u) { if(u!=null) { u.able(); u.enable(); } } }
package com_package1; public interface USB { public void able(); public void enable(); }
package com_package1; public class UDisk implements USB { @Override public void able() { // TODO Auto-generated method stub System.out.println("disk able"); } @Override public void enable() { // TODO Auto-generated method stub System.out.println("disk enable"); } }
package com_package1; public class Umouse implements USB{ @Override public void able() { // TODO Auto-generated method stub System.out.println("mouse able"); } @Override public void enable() { // TODO Auto-generated method stub System.out.println("mouse enable"); } }
package com_package1; public class NoteBookDemo { public static void main(String[]args) { NoteBook nt = new NoteBook(); nt.run(); // nt.useUSB(u); nt.useUSB(null); nt.useUSB( new UDisk()); nt.useUSB(new Umouse()); } }
时间: 2024-10-13 14:35:45