面向接口编程之打印机(二)

面向接口编程之打印机(二)_第1张图片1.按照图上首先定义两个接口:墨盒,纸张接口

package com.inter2;
/**
 * 定义墨盒接口
 */
public interface InkBox {
    String color();
}

package com.inter2;
/**
 * 定义纸张接口
 */
public interface Paper {
    String sheet();
}

2.当然是实现接口了:

package com.inter2;
/**
 * 实现墨盒的接口
 */
public class InkBoxImpl implements InkBox {
    public String color(){
        return "彩色";
    }
}

package com.inter2;
/**
 * 实现纸张的接口
 */
public class PaperImpl implements Paper {
    public String sheet(){
        return "A4纸";
    }
}

3.定义打印机类

package com.inter2;
/**
 * 打印机类
 */
public class Printer {
    Paper paper;
    InkBox inkBox;
    //有参构造方法
    public Printer(PaperImpl paper, InkBoxImpl inkBox) {
        this.paper = paper;
        this.inkBox = inkBox;
    }
    //打印输出方法
    public String print() {
        return "使用" + inkBox.color() + "墨盒在" + paper.sheet() + "上打印";
    }
}

4.测试:

package com.inter2;

/**
 * 测试2
 */
public class Text {
    public static void main(String[] args) {

        Printer printer = new Printer(new PaperImpl(),new InkBoxImpl());
        //打印输出
        System.out.println(printer.print());
    }
}

你可能感兴趣的:(java)