9、从零开始学习JAVA--面向对象的应用

解决实际开发过程中的重复代码问题

参考客户要求开发打印机程序的例子

注意继承、this、super的用法

不使用面向对象的开发:

class HpPrinter
{
	void open()
	{
		System.out.println("Open");
	}

	void close()
	{
		System.out.println("Close");

	}
	
	void print(String s)
	{
		System.out.println("print-->" + s);

	}
}
class CanonPrinter
{
	void open()
	{
		System.out.println("Open");
	}

	void close()
	{
		this.clean();
		System.out.println("Close");

	}
	
	void print(String s)
	{
		System.out.println("print-->" + s);

	}

	void clean()
	{
		System.out.println("Clean");
	}
}
class Test
{
	public static void main(String[] args)
	{	
		int flag = 1;

		if(0 == flag)
		{
			HpPrinter hpPrinter = new HpPrinter();
			hpPrinter.open();
			hpPrinter.print("我是你的小小狗");
			hpPrinter.close();	
		}
		else
		{
			CanonPrinter canonPrinter = new CanonPrinter();
			canonPrinter.open();
			canonPrinter.print("你是我骨头");
			canonPrinter.close();
		}

	}
}

使用面向对象思想后:

class Printer
{
	void open()
	{
		System.out.println("Open");
	}

	void close()
	{
		System.out.println("Close");

	}
	
	void print(String s)
	{
		System.out.println("print-->" + s);

	}
}
class HpPrinter extends Printer
{
}
class CanonPrinter extends Printer
{
	void close()
	{
		this.clean();
		super.close();

	}

	void clean()
	{
		System.out.println("Clean");
	}
}
class Test
{
	public static void main(String[] args)
	{	
		int flag = 0;

		if(0 == flag)
		{
			HpPrinter hpPrinter = new HpPrinter();
			hpPrinter.open();
			hpPrinter.print("我是你的小小狗");
			hpPrinter.close();	
		}
		else
		{
			CanonPrinter canonPrinter = new CanonPrinter();
			canonPrinter.open();
			canonPrinter.print("你是我骨头");
			canonPrinter.close();
		}

	}
}

你可能感兴趣的:(java)