新手入门JAVA题,在线等200分

来源:百度知道 编辑:UC知道 时间:2024/06/04 15:34:33
阅读如下代码后回答:
public interface Animal{
void voice();
}
class Dog implements Animal{
public void voice(){
System.out.println("W W!");
}
class Cat implements Animal{
public void voice(){
System.out.println("M M!");
}
}
Class Store{
public static Animal get(String choice){
if(choice.equalsIgnoreCase("dog")) {
return new Dog();
}else {
return new Cat();
}
}
}
public class AnimalTest {
public static void main(String args[]){
Animal a1 = Store.get("dog");
a1.voice();
}
}
题目:
在上面代码中增加一种新的动物类型:Pig(猪),实现voice()方法、修改Store(商店)类的get方法:如果传入的参数是字符串dog.则返回一个Dog对象;如果传入的参数是字符串pig,则返回一个Pig对象;否则返回一个Cat对象。在测试类 Animal2Test中加以测试,向Store的get方法中传入参数pig,并在返回的对象上调用voice方法,看看与预期的结果是否一致。
********************************************

public interface Animal {
void voice();
}
-----------------
public class Cat implements Animal {

public void voice() {
System.out.println("M M!");
}

}
--------------------------
public class Dog implements Animal {

public void voice() {
System.out.println("W W!");
}

}
-------------------------
public class Pig implements Animal {

public void voice() {
System.out.println("is pig!");
}

}
-----------------------------
public class Store {

public static Animal get(String choice) {
if("dog".equals(choice))
{
return new Dog();
}
else if("pig".equals(choice))
{
return new Pig();
}
else
{
return new Cat();
}
}
}

--------------------------------------
p