1.在第三题的进行功能扩展。
public interface Animal {
void shout();
}
public class Dog implements Animal {
public void shout() {
System.out.println("W W!");
}
}
public class Cat implements Animal {
public void shout() {
System.out.println("M M!");
}
}
public class Pig implements Animal {
public void shout() {
System.out.println("N N!");
}
}
public class Store {
public static Animal get(String animal) {
if(animal.equalsIgnoreCase("dog")) {
return new Dog();
}else if(animal.equalsIgnoreCase("pig")){
return new Pig();
}else {
return new Cat();
}
}
}
public class AnimalTest {
public static void main(String[] args) {
Animal animal = Store.get("pig");
animal.shout();
}
}
2..使用面向接口思想对电子宠物系统类结构进行重构
package bdqn.com;
/**
*
* @author 宠物类
*
*/
public abstract class chonwu {
protected String name = "无名氏";
protected int health =100;
protected int love = 0;
public Pet(String name) {
this.name = name;
}
/**
* 输出宠物信息
*/
public void print() {
System.out.println("我的名字叫"+this.name+",健康值是"+this.health+",和主人的亲密度是"+this.love);
}
}
package bdqn.com;
/**
*
* @author 狗狗类
*
*/
public class Dog extends Pet implements Eatable,Flying{
private String strain; //品种
public Dog(String name,String strain) {
super(name);
this.strain = strain;
}
public void print() {
super.print();
System.out.println("我是一只"+this.strain);
}
@Override
public void flyDis() {
// TODO Auto-generated method stub
super.health = super.health-10;
System.out.println("和狗狗玩接飞盘的游戏!狗狗健康值减10");
}
@Override
public void eat() {
// TODO Auto-generated method stub
super.health = super.health+3;
System.out.println("喂狗狗吃狗粮!狗狗健康值加3");
}
}
package bdqn.com;
/**
*
* @author 企鹅类
*
*/
public class Penguin extends Pet implements Eatable,Swimmable{
private String sex;
public Penguin(String name,String sex) {
super(name);
this.sex = sex;
}
public void print() {
super.print();
System.out.println("我的性别是:"+this.sex);
}
@Override
public void swin() {
// TODO Auto-generated method stub
super.health = super.health-10;
System.out.println("和企鹅玩游泳游戏!企鹅健康值减10");
}
@Override
public void eat() {
// TODO Auto-generated method stub
super.health = super.health+3;
System.out.println("喂企鹅吃鱼!企鹅健康值加3");
}
}
package bdqn.com;
/**
* 吃饭的接口
* @author 接口
*
*/
public interface Eatable {
void eat(); //吃饭功能
}
package bdqn.com;
/**
* 接飞盘接口
* @author 接口
*
*/
public interface Flying {
void flyDis(); //接飞盘
}
package bdqn.com;
/**
* 游泳的接口
* @author 接口
*
*/
public interface Swimmable {
void swin(); //游泳
}
package bdqn.com;
/**
*
* @author 测试类
*
*/
public class TestFeed {
public static void main(String[] args) {
Dog pet = new Dog("黑宝","拉布拉多犬");
pet.print();
pet.eat();
pet.flyDis();
System.out.println();
Penguin pet1 = new Penguin("楠楠","Q妹");
pet1.print();
pet1.eat();
pet1.swin();
}
}