java(2)之前往對象村,java前往對象村

來源:互聯網
上載者:User

java(2)之前往對象村,java前往對象村

這次說一說物件導向與面向過程的區別以及物件導向的優點。

聽一聽用面向過程思想編程的程式員寫程式時的心聲:What are the things this program has to do? What procedures do we need?

啊哈,作為一名合格的准java程式員的我的想法是:What are the things in this program......who are the key players?

從中,可以形象的體現出物件導向與面向過程的區別。面向過程寫程式時,關心的是程式按什麼順序做哪些事情,而物件導向的程式是關注程式中有哪些事物(正規叫法是類)。

比如,專案經理要給你個需求,要求寫個圖形(三角形,正方向,圓形)旋轉同時播放音樂(mp3格式)的程式(你在播放器中常看到的,播放音樂時,歌手的頭像在轉動)。

作為一個資深的C語言玩家的小碼同學,稍加思索就找到啦這個程式的兩個重要過程:圖形旋轉,播放音樂。so  his program is:

 

rotate(shapeNum) {

  // make the shape rotate 360º

}

playSound(shapeNum) {

  // use shapeNum to lookup which

     // AIF sound to play, and play it

 

 

}

 

 

我思考很久,也找到了其中的類:圖形。(哈哈)

繼續按著物件導向的思想思索,這個類有什麼屬性呢?需求裡沒提吧。類的行為呢?有旋轉,和放音樂的行為。嗯,分析完就寫程式啦。

class cirlce {

  ratate() {

    //code to ratate a circle

     }

  playSound() {

    //code to ratate a circle

  }

}

 

class Square {

 

  ratate() {

 

    //code to ratate a circle

 

     }

 

  playSound() {

 

    //code to ratate a circle

 

  }

 

 

 

 

 

 

 

 

 

 

現在專案經理說需求有變

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

物件導向三大特性中的:繼承,多態,讓代碼的複用率提高了老多。

物件導向優點非常非常的多,自己可以去深深體驗一下,編程學習中自己嘗試是非常非常重要的。

 

一個小建議:

If you’re stuck on an exercise, try talking about it out loud. Speaking (and hearing) activates a different part of your brain. Although it works best if you have another person to discuss it with, pets work too. That’s how our dog learned polymorphism.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.