主要体现在,调用时通过:父类名 实例名=new 子类名(形参);
将父类实例化为子类(本身还是父类实例),再使用这个父类实例作为方法参数,去调用其他类的方法体中父类的方法(或属性);
此时实际上发生作用的是子类中重写的方法(或属性)。
以下是例题:
package ch13.day0801.zy.zy03;
public class Test {
public static void main(String[] args) {
Printer d=new DotMatrixPrinter("慢","差","高");
Printer i=new InkpetPrinter("一般","一般","一般");
Printer l=new LaserPrinter("快","好","低");
User user=new User();
user.showDoc(d);
user.showDoc(i);
user.showDoc(l);
}
}
结果为:
针式打印机--打印速度慢,效果差,噪音高
喷墨打印机--打印速度一般,效果一般,噪音一般
激光打印机--打印速度快,效果好,噪音低
package ch13.day0801.zy.zy03;
public class User {
public void showDoc(Printer p) {
p.print();
}
}
package ch13.day0801.zy.zy03;
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 ch13.day0801.zy.zy03;
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 ch13.day0801.zy.zy03;
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);
}
}
package ch13.day0801.zy.zy03;
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;
}
}