class Demo3_AnimalJump {
public static void main(String[] args) {
method(new Cat("猫",2));
method(new CatJump("跳高猫",3));
method(new Dog("狗",4));
method(new DogJump("跳高狗",5));
}
public static void method1(Animal a){
a.show();
a.eat();
a.sleep();
}
public static void method(Animal a){
if (a instanceof CatJump) {
method1(a);
CatJump cj =(CatJump)a;
cj.jump();
}else if (a instanceof DogJump) {
method1(a);
DogJump dj =(DogJump)a;
dj.jump();
}else {
method1(a);
}
}
}
/*
* A:案例演示
* 动物类:姓名,年龄,吃饭,睡觉。
* 猫和狗
* 动物培训接口:跳高
*/
class Animal {
private String name;
private int age;
public Animal(){}
public Animal(String name,int age){
this.name = name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void eat(){
System.out.println("吃饭");
}
public void sleep(){
System.out.println("睡觉");
}
public void show(){
System.out.println("品种:"+getName()+",年龄:"+getAge());
}
}
interface Jump {
public abstract void jump();
}
class Cat extends Animal {
private String name;
private int age;
public Cat(){}
public Cat(String name,int age){
super(name,age);
}
public void eat(){
System.out.println("猫吃鱼");
}
public void sleep(){
System.out.println("猫睡觉");
}
}
class CatJump extends Cat implements Jump {
private String name;
private int age;
public CatJump(){}
public CatJump(String name,int age){
super(name,age);
}
public void jump(){
System.out.println("猫跳高");
}
}
class Dog extends Animal{
private String name;
private int age;
public Dog(){}
public Dog(String name,int age){
super(name,age);
}
public void eat(){
System.out.println("狗吃肉");
}
public void sleep(){
System.out.println("狗睡觉");
}
}
class DogJump extends Dog implements Jump {
private String name;
private int age;
public DogJump(){}
public DogJump(String name,int age){
super(name,age);
}
public void jump(){
System.out.println("狗跳高");
}
} |
|