(笔记)多态:向上转型,返回值类型实现多态(工厂方法)
程序员文章站
2024-02-19 08:02:04
...
以下是例题:
以下类都在同一包中:
使用Factory类,将个子类实例化并赋值给一个父类实例,并将此父类实例作为返回值,然后在Test类中用此返回值调用抽象方法。
package day0802.ch13.lx.lx01;
public class Test {
public static void main(String[] args) {
Factory factory=new Factory();
factory.generate(1).print();;
factory.generate(2).print();
factory.generate(3).print();
}
}
运行结果:
针式打印机--打印速度慢,效果差,噪音高
喷墨打印机--打印速度一般,效果一般,噪音一般
激光打印机--打印速度快,效果好,噪音低
package day0802.ch13.lx.lx01;
public class Factory {
public Printer generate(int i) {
Printer p=null;
if(i==1) {
p=new DotMatrixPrinter("慢","差","高");
}else if(i==2) {
p=new InkpetPrinter("一般","一般","一般");
}else if(i==3) {
p=new LaserPrinter("快","好","低");
}
return p;
}
}
package day0802.ch13.lx.lx01;
public abstract class Printer {
private String speed;
private String effect;
private String noise;
public abstract void print();
//构造方法
public Printer(){}
public Printer(String speed, String effect, String noise) {
super();
this.speed = speed;
this.effect = effect;
this.noise = noise;
}
//get set
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getEffect() {
return effect;
}
public void setEffect(String effect) {
this.effect = effect;
}
public String getNoise() {
return noise;
}
public void setNoise(String noise) {
this.noise = noise;
}
}
package day0802.ch13.lx.lx01;
public class DotMatrixPrinter extends Printer {
@Override
public void print() {
System.out.println("针式打印机--打印速度"+this.getSpeed()+",效果"+this.getEffect()+",噪音"+this.getNoise());
}
//构造方法
public DotMatrixPrinter() {}
public DotMatrixPrinter(String speed, String effect, String noise) {
super(speed,effect,noise);
}
}
package day0802.ch13.lx.lx01;
public class InkpetPrinter extends Printer {
@Override
public void print() {
System.out.println("喷墨打印机--打印速度"+this.getSpeed()+",效果"+this.getEffect()+",噪音"+this.getNoise());
}
//构造方法
public InkpetPrinter() {}
public InkpetPrinter(String speed, String effect, String noise) {
super(speed,effect,noise);
}
}
package day0802.ch13.lx.lx01;
public class LaserPrinter extends Printer {
@Override
public void print() {
System.out.println("激光打印机--打印速度"+this.getSpeed()+",效果"+this.getEffect()+",噪音"+this.getNoise());
}
//构造方法
public LaserPrinter() {}
public LaserPrinter(String speed, String effect, String noise) {
super(speed,effect,noise);
}
}