《Java4android》視頻學習筆記——物件導向的應用(一)

來源:互聯網
上載者:User

標籤:

---恢複內容開始---

有一台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》視頻學習筆記——物件導向的應用(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.