Java:利用接口实现打印机案例(墨盒有彩色和黑白色,纸张有A4纸和B5纸)

把纸张和墨盒都定义为接口,让以后的实现类去实现它。

package com.jredu.oop.ch03;
/**
 * 纸张接口
 * @author Administrator
 *
 */
public interface Paper {

	/**
	 * 纸张
	 */
	void paper();
	
}
package com.jredu.oop.ch03;

public class A4Paper implements Paper{

	@Override
	public void paper() {
		// TODO Auto-generated method stub
		System.out.println("组装一个A4纸盒");
	}

}

package com.jredu.oop.ch03;

public class B5Paper implements Paper {

	@Override
	public void paper() {
		// TODO Auto-generated method stub
		System.out.println("组装一个B5纸盒");
	}

}

package com.jredu.oop.ch03;
/**
 * 墨盒接口
 * @author Administrator
 *
 */
public interface Ink {

	/**
	 * 墨盒
	 */
	void ink();
	
}

package com.jredu.oop.ch03;

public class ColorInk implements Ink{

	@Override
	public void ink() {
		// TODO Auto-generated method stub
		System.out.println("组装一个彩色墨盒");
	}

}
package com.jredu.oop.ch03;

public class BlackInk implements Ink{

	@Override
	public void ink() {
		// TODO Auto-generated method stub
		System.out.println("组装一个黑白墨盒");
	}

}

打印类:

package com.jredu.oop.ch03;

public class Printer {
	
	private Ink ink;//墨盒
	private Paper paper;//纸张
	
	public Printer(Ink ink, Paper paper) {
		super();
		this.ink = ink;
		this.paper = paper;
	}



	public void print() {
		ink.ink();
		paper.paper();
		System.out.println("打印机开始工作");
	}

}
测试类:

package com.jredu.oop.ch03;

public class PrinterTest {
	
	public static void main(String[] args) {
		ColorInk color=new ColorInk();
		BlackInk black=new BlackInk();
		A4Paper a4=new A4Paper();
		B5Paper b5=new B5Paper();
		Printer printer=new Printer(black, a4);
		printer.print();
	}

}





展开阅读全文

没有更多推荐了,返回首页