package package1;
public class Demo11 {
public static void main(String[] args) {
ColorPrinter color=new ColorPrinter("联想");
BlackPrinter blck=new BlackPrinter("惠普");
School stu=new School();
//stu.setColorPrinter(color);
stu.setBlackPrinter(blck);
stu.print("hello java");
}
}
class Printer{
private String brand;
public Printer(String brand) {
this.brand=brand;
}
public String getPrint() {
return brand;
}
//此打印方法有子类来实现
public void print(String content) {
}
}
class ColorPrinter extends Printer{
public ColorPrinter(String brand) {
super(brand);
}
//对父类方法进行重写
public void print(String content) {
System.out.println(getPrint()+"彩色打印"+content);
}
}
class BlackPrinter extends Printer{
public BlackPrinter(String brand) {
super(brand);
}
//对父类方法进行重写
public void print(String content) {
System.out.println(getPrint()+"黑白打印"+content);
}
}
class School{
private ColorPrinter cP=null;
private BlackPrinter bP=null;
//安装彩色打印机
public void setColorPrinter(ColorPrinter cp) {
this.cP=cp;
}
//安装黑白打印机
public void setBlackPrinter(BlackPrinter bp) {
this.bP=bp;
}
public void print(String content) {
bP.print(content);
}
}
以上是彩色打印机和黑白打印机的实现,如果在加入一台针式打印机那么又得进行添加一个类(针式打印机的类),而且在学校这个类中添加属性。如此一来不断的添加打印机不断添加类太麻烦,那么用多态来实现改进这一麻烦的过程。
package package1;
public class Demo11 {
public static void main(String[] args) {
ColorPrinter color=new ColorPrinter("联想");
BlackPrinter blck=new BlackPrinter("惠普");
School stu=new School();
//stu.setPrinter(color);
stu.setPrinter(blck);
stu.print("hello java");
}
}
class Printer{
private String brand;
public Printer(String brand) {
this.brand=brand;
}
public String getPrint() {
return brand;
}
//此打印方法有子类来实现
public void print(String content) {
}
}
class ColorPrinter extends Printer{
public ColorPrinter(String brand) {
super(brand);
}
//对父类方法进行重写
public void print(String content) {
System.out.println(getPrint()+"彩色打印"+content);
}
}
class BlackPrinter extends Printer{
public BlackPrinter(String brand) {
super(brand);
}
//对父类方法进行重写
public void print(String content) {
System.out.println(getPrint()+"黑白打印"+content);
}
}
class School{
/*
private ColorPrinter cP=null;
private BlackPrinter bP=null;
*/
//改进后:直接写父类的引用变量(学校安装打印机)
private Printer p=null;
/*
* //安装彩色打印机
public void setColorPrinter(ColorPrinter cp) {
this.cP=cp;
}
//安装黑白打印机
public void setBlackPrinter(BlackPrinter bp) {
this.bP=bp;
}*/
//写一个通用的方法,拿父类的引用变量作为参数,好处就是可以接受任何其子类对象
public void setPrinter(Printer p) {
this.p=p;
}
public void print(String content) {
p.print(content);
}
}
通过多态使程序有更好的可维护性和扩展性