Java 4android video learning notes-object-oriented applications (I), java object-oriented notes
--- Restore content start ---
There is an HP printer that requires a program to enable boot, printing, and shutdown.
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 ();}}
Later, a Canon printer needs to be turned on, printed, cleaned, and 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 can we use the same program to implement the functions of the 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 an equal sign must be used here.
Hp. open ();
Hp. print ("abc ");
Hp. close ();
}
Else if (a = 0 ){
Canon. open ();
Canon. print ("123 ");
Canon. close ();
}
}
}
The above program has a lot of repeated code. If there are a lot of different printers to add, it is easy to change a program, it is also easy to change two programs, it is always impossible to change each program again? In fact, we can minimize the risk and eliminate the repeated code.
Create a parent Printer
Class Printer
{
Void open (){
System. out. println ("Open ");
}
Void print (String s ){
System. out. println ("Print -->" + s );
}
Void close (){
System. out. println ("Close ");
}
}
Inherit all types of printers
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 ();
}
}
}
So far
--- Restore content end ---