宠物类例题
public class Person { private String name; private Pet pet; public Person() {} public Person(String name,Pet pet){ this.name=name; this.pet=pet; } public void petHappy(){ pet.scream(); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public abstract class Pet { private String pname; public Pet(){} public Pet(String pname){ this.pname = pname; } public abstract void scream();/*{ System.out.println("宠物的叫声"); }*/ public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } }
public class Tiger extends Pet{ public String fur; public Tiger(String fur,String name) { super(name); this.fur = fur; } public Tiger() { super(); } @Override public void scream() { System.out.println("这是一只老虎的叫声"); } public String getFur() { return fur; } public void setFur(String fur) { this.fur = fur; } }
public class Main { public static void main(String[] args){ Tiger t1 =new Tiger(); Rabbit t2 = new Rabbit(); Person p1 = new Person("小明",t1); Person p2 = new Person("小红",t2); p1.petHappy(); p2.petHappy(); } }