CatFactory.getCatByKey(key),可以使用"类名.方法名"的方式,也可以使用"对象名.方法名"的方式。
package zh.codegym.task.task14.task1404;
/*
猫
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws Exception {
//在此编写你的代码
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String key;
while (!(key = reader.readLine()).equals("")) {
Cat cat = CatFactory.getCatByKey(key);
System.out.println(cat.toString());
}
}
static class CatFactory {
static Cat getCatByKey(String key) {
Cat cat;
switch (key) {
case "凶爪":
cat = new MeanCat("利爪");
break;
case "米斯":
cat = new NiceCat("米西");
break;
case "斯马奇":
cat = new NiceCat("斯马戈");
break;
default:
cat = new Cat(key);
break;
}
return cat;
}
}
static class Cat {
private String name;
protected Cat(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return "我是" + getName() + ",一只小巷猫";
}
}
static class MeanCat extends Cat {
MeanCat(String name) {
super(name);
}
public String toString() {
return "我是" + getName() + ",我要挖掉你的眼睛";
}
}
static class NiceCat extends Cat {
NiceCat(String name) {
super(name);
}
public String toString() {
return "我是一只可爱的小猫,我叫" + getName();
}
}
}