训练15 汽车厂、鞋厂都是工厂
创建抽象的工厂类,工厂类有一个抽象的生产方法。让汽车厂和鞋厂都继承工厂类,汽车厂生产汽车,鞋厂生产鞋。
public class AutoPlant extends Factory {
String productsName;
public AutoPlant(String productsName) {
this.productsName = productsName;
}
@Override
public String produce() {
return this.productsName;
}
}
public abstract class Factory {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract String produce();
}
public class ShoeFactory extends Factory {
String productsName;
public ShoeFactory(String productsName) {
this.productsName = productsName;
}
@Override
public String produce() {
return this.productsName;
}
}
public class Test {
public static void main(String[] args) {
AutoPlant autoPlant = new AutoPlant("汽车");
autoPlant.setName("汽车厂");
System.out.println(autoPlant.getName() + "生产的是" + autoPlant.productsName);
ShoeFactory shoeFactory = new ShoeFactory("鞋");
shoeFactory.setName("鞋厂");
System.out.println(shoeFactory.getName() + "生产的是" + shoeFactory.productsName);
}
}
训练16 五颜六色的接口
创建一个五颜六色的接口Colorful,接口中有一个表示点亮的抽象方法shine()。编写一段代码,实现红灯发红光,黄灯发黄光,绿灯发绿光。
interface Colorful {
void shine();
}
class RedLights implements Colorful {
@Override
public void shine() {
System.out.println("红灯亮红光");
}
}
class YellowLights implements Colorful {
@Override
public void shine() {
System.out.println("黄灯亮黄光");
}
}
class GreenLights implements Colorful {
@Override
public void shine() {
System.out.println("绿灯亮绿光");
}
}