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.