天天看點

Thinking in Java 讀書筆記(1)

第一章:對象導論

面向對象程式設計五個基本特性:

1、 Everything is a object. Think of a object as a fancy variable;it stores data,but you can “make requests” to that object,asking it to perform operations on itself.In theory,you can take any conceptual component in the problem you’re trying to solve and represent it as an object in your program.

2、A program is a bunch of objects telling each other what to do by sending messages. To make a request of an object, you “send a message” to that object. More concretely, you can think of a message as a request to call a method that belongs to a particular object.

3、Each object has its own memory made up of other objects. Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the simplicity of objects.

4、Every object has a type. Using the parlance, each object is an instance of a class, in which “class” is synonymous with “type.” The most important distinguishing characteristic of a class is “What messages can you send to it?”

5、All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type “circle” is also an object of type “shape,” a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the powerful concepts in OOP

一個對象還包括狀态、行為、特性。類是具有相同特性(資料元素)和行為(功能)的對象的集合。它是一種資料類型。每個對象都隻滿足某些請求,這些請求由對象的接口(Interface)所定義,決定接口的便是類型。

   每一對象都提供服務,将對象看作服務提供者

隐藏具體實作:

   通路控制:

作用域 目前類 同一package 子孫類 其他package
public
protected ×
friendly × ×
private × × ×

複用具體實作:

    1、建立新類時首先考慮組合而不是繼承

2、繼承複用接口

繼承現有類型時,也就創造了新的類型。這個新的類型不僅包括現有類型的所有成員(盡管private成員被隐藏起來并且不可通路),更重要的是它複制了基類的接口,所有可以發送給基類對象的消息同時也可以發送給導出類,意味着導出類與基類有相同的類型

3、重載(Overriding)

導出類重新定義基類中的方法,使之在新類型中可以完成不同的任務。

導出類完全替代基類中的方法,是is-a的關系;導出類中添加新方法而基類無法通路,是is-like-a關系;

4、多态

不依賴于特定類型的代碼就是把一個對象不當作它所屬的特定類型來對待,而是将其當作基類的對象來對待。在OOP中,程式直道運作時刻才能夠确定代碼的位址,是以當消息發送到一個範化對象時,采用“後期綁定(late binding)”

。當向對象發送消息時,被調用代碼直到運作時刻才能被确定,編譯器確定被調用方法存在,并對調用參數(argument)和傳回值(return value)執行類型檢查(無法提供此類保證的語言稱作弱類型),但是并不知道确切要執行的代碼。

Java中使用一小段代碼來替代絕對位址調用,實作後期綁定。

向上轉型(upcasting)

    5、抽象基類和接口

不希望任何人建立基類的實際對象,隻是希望對象向上轉型到基類,就使用接口。使用abstract關鍵字來辨別抽象類,也可以表示尚未被實作的方法。

抽象方法隻能在抽象類中實作,當該類被繼承時抽象方法必須被實作,否則繼承類依然是抽象類。

Interface根本不容許有任何方法定義。

對象的建立、使用和生命周期

分為兩種方式:

1、為了追求最大的執行速度,對象的存儲空間和生命周期在編寫程式時确定。通過将對象置于堆棧或靜态存儲區内來實作。

2、在被稱作堆的記憶體池中動态地建立對象,垃圾收集機制。直到運作時刻才知道需要多少對象、它們的生命周期、它們的具體類型,隻有在程式運作時相關代碼被執行到的那一刻才能确定。

單根繼承結構

    所有的類都繼承自一個基類