---restore content starts---
One HP printer requires a program to power on, print, and shut down these three functions
Class Hpprinter{void Open () {System.out.println ("open");} void print (String s) {System.out.println ("print-->" + s);} void Close () {System.out.println ("close");}}
Class Test{public static void Main (String args[]) {hpprinter hp = new Hpprinter (); Hp.open (); Hp.print ("abc"); Hp.close ();}}
Then another canon printer needs to be switched on, printed, cleaned, shut down
Class Canonprinter
{
void Open () {
System.out.println ("Open");
}
void print (String s) {
System.out.println ("print-->" + s);
}
void Close () {
This.clean ();
System.out.println ("Close");
}
void Clean () {
System.out.println ("clean");
}
}
How to use the same program to achieve the functions of these two printers?
Class Test
{
public static void Main (String args[])
{
int a = 0;
Hpprinter hp = new Hpprinter ();
Canonprinter canon = new Canonprinter ();
if (a = = 1) {//note that the equals sign is required here.
Hp.open ();
Hp.print ("abc");
Hp.close ();
}
else if (a = = 0) {
Canon.open ();
Canon.print ("123");
Canon.close ();
}
}
}
The above procedure has a lot of duplicate code, if there are a lot of different printers add in, change a program easy, change two programs also easy, can not be changed every program it? In fact, we can reduce the risk to a minimum, solve the duplication of code.
Build a parent class printer
Class Printer
{
void Open () {
System.out.println ("Open");
}
void print (String s) {
System.out.println ("print-->" + s);
}
void Close () {
System.out.println ("Close");
}
}
Let all kinds of printers inherit
Class Hpprinter extends Printer
{
}
Class Canonprinter extends Printer
{
void Close () {
This.clean ();
Super.close ();
}
void Clean () {
System.out.println ("clean");
}
}
Main function
Class Test
{
public static void Main (String args[])
{
int a = 0;
Hpprinter hp = new Hpprinter ();
Canonprinter canon = new Canonprinter ();
if (a = = 1) {
Hp.open ();
Hp.print ("abc");
Hp.close ();
}
else if (a = = 0) {
Canon.open ();
Canon.print ("123");
Canon.close ();
}
}
}
Complete
---restore content ends---
"Java4android" Video Learning Notes-object-oriented application (i)