標籤:
---恢複內容開始---
有一台HP印表機需要一個程式來實現開機,列印,關機這三個功能
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();}}
後來又來一台Canon印表機需要實現開機,列印,清理,關機
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");
}
}
如何用同一個程式實現這兩台印表機的功能呢?
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();
}
}
}
上述程式有很多的重複代碼,要是有很多種不同的印表機加進來,改一個程式容易,改兩個程式也容易,總不能每個程式改一遍的吧?其實我們完全可以把風險降到最低,解決掉這些重複代碼。
建一個父類Printer
class Printer
{
void open(){
System.out.println("Open");
}
void print(String s){
System.out.println("Print-->" + s);
}
void close(){
System.out.println("Close");
}
}
讓各類印表機繼承
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 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();
}
}
}
至此完成
---恢複內容結束---
《Java4android》視頻學習筆記——物件導向的應用(一)