java实训第七次作业(宠物店领养动物)

需求:升级宠物商店 -------------instanceof:判断某对象是否实现了某个接口(boolean=obj instanceof 接口)
        a,新增动物:小海豚、小鱼
        b,领养成功后,有腿的动物需要输出腿的数量

public interface Animal {
	void eat();
}
public interface Animal1 extends Animal {
	void shout();
}

 

public interface Animal2 extends Animal {
	int getLeg();
}
public class Cat implements Animal1,Animal2 {
	public void shout(){
		System.out.println("喵喵~");
	}

	public int getLeg() {
		// TODO Auto-generated method stub
		return 4;
	}

	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("我吃鱼。");
	}
}
public  class Pig implements Animal1,Animal2 {
	public void shout(){
		System.out.println("哼哼~,我是小猪,");
	}

	public int getLeg() {
		// TODO Auto-generated method stub
		return 4;
	}

	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("我吃饲料。");
	}
}
public class Dog implements Animal1,Animal2 {
	public void shout(){
		System.out.println("旺旺~,我是小狗,");
	}

	public int getLeg() {
		// TODO Auto-generated method stub
		return 4;
	}

	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("我吃肉。");
	}
}
public class Fish implements Animal {
	public void eat() {
		// TODO Auto-generated method stub
		System.out.print("我是小鱼,我吃蚯蚓。");
	}	
}
public class Dolphin implements Animal1 {

	public void eat() {
		// TODO Auto-generated method stub
		System.out.print("我吃鱼。");
	}

	public void shout() {
		// TODO Auto-generated method stub
		System.out.print("吱吱~,我是海豚,");
	}	
}

public class Shop {
	public Animal get(int choice){
		if(choice==1){
			return new Dog();
		}else if(choice==2){
			return new Pig();
		}else if(choice==3){
			return new Cat();
		}else if(choice==4){
			return new Dolphin();	
		}else {
			return new Fish();
		}
	}

}

 测试类

import java.util.Scanner;
public class Test {
	public static void main(String[]args){
		System.out.println("请选择您要领养的小动物:\n1,小狗\n2,小猪\n3,小猫\n4,海豚\n5,鱼");
		Scanner sc=new Scanner(System.in);
		int choice=sc.nextInt();
		Shop s=new Shop();
		Animal a=s.get(choice);	
		//判断并输出。
		if((a instanceof Animal1)&&(a instanceof Animal2)){
			a.eat();
			((Animal1)a).shout();
			System.out.println("我有"+((Animal2)a).getLeg()+"条腿");
		}else if(a instanceof Animal1){
			((Animal1)a).shout();a.eat();
			System.out.println("我没有腿");
		}else{
			a.eat();
			System.out.println("我不会叫,我没有腿哦。");
	
	}
    }
}

 

你可能感兴趣的:(java实训第七次作业(宠物店领养动物))