外文翻譯模板_第1頁
外文翻譯模板_第2頁
外文翻譯模板_第3頁
外文翻譯模板_第4頁
外文翻譯模板_第5頁
已閱讀5頁,還剩6頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、Think in JavaBy Bruce EckelSource: http:/1.Everything Is an ObjectAlthough it is based on C+, Java is more of a “pure” object-oriented language. Both C+ and Java are hybrid languages, but in Java the designers felt that the hybridization was not as important as it was in C+. A hybrid language allows

2、 multiple programming styles; the reason C+ is hybrid is to support backward compatibility with the C language. Because C+ is a superset of the C language, it includes many of that languages undesirable features, which can make some aspects of C+ overly complicated. The Java language assumes that yo

3、u want to do only object-oriented programming. This means that before you can begin you must shift your mindset into an object-oriented world (unless its already there). The benefit of this initial effort is the ability to program in a language that is simpler to learn and to use than many other OOP

4、 languages. In this chapter youll see the basic components of a Java program and learn that (almost) everything in Java is an object.2.You manipulate objects with references Each programming language has its own means of manipulating elements in memory. Sometimes the programmer must be constantly aw

5、are of what type of manipulation is going on. Are you manipulating the element directly, or are you dealing with some kind of indirect representation (a pointer in C or C+) that must be treated with a special syntax? All this is simplified in Java. You treat everything as an object, using a single c

6、onsistent syntax. Although you treat everything as an object, the identifier you manipulate is actually a “reference” to an object.1 You might imagine a television (the object) and a remote control (the reference). As long as youre holding this reference, you have a connection to the television, but

7、 when someone says, “Change the channel” or “Lower the volume,” what youre manipulating is the reference, which in turn modifies the object. If you want to move around the room and still control the television, you take the remote/reference with you, not the television.Also, the remote control can s

8、tand on its own, with no television. That is, just because you have a reference doesnt mean theres necessarily an object connected to it. So if you want to hold a word or sentence, you create a String reference: String s; But here youve created only the reference, not an object. If you decided to se

9、nd a message to s at this point, youll get an error because s isnt actually attached to anything (theres no television). A safer practice, then, is always to initialize a reference when you create it: String s = "asdf" However, this uses a special Java feature: Strings can be initialized w

10、ith quoted text. Normally, you must use a more general type of initialization for objects.3.You must create all the objects When you create a reference, you want to connect it with a new object. You do so, in general, with the new operator. The keyword new says, “Make me a new one of these objects.”

11、 So in the preceding example, you can say: String s = new String("asdf"); Not only does this mean “Make me a new String,” but it also gives information about how to make the String by supplying an initial character string. Of course, Java comes with a plethora of ready-made types in additi

12、on to String. Whats more important is that you can create your own types. In fact, creating new types is the fundamental activity in Java programming, and its what youll be learning about in the rest of this book.(1)Where storage lives Its useful to visualize some aspects of how things are laid out

13、while the program is runningin particular how memory is arranged. There are five different places to store data: 1)Registers. This is the fastest storage because it exists in a place different from that of other storage: inside the processor. However, the number of registers is severely limited, so

14、registers are allocated as they are needed. You dont have direct control, nor do you see any evidence in your programs that registers even exist (C & C+, on the other hand, allow you to suggest register allocation to the compiler). 2)The stack.This lives in the general random-access memory (RAM)

15、 area, but has direct support from the processor via its stack pointer. The stack pointer is moved down to create new memory and moved up to release that memory. This is an extremely fast and efficient way to allocate storage, second only to registers. The Java system must know, while it is creating

16、 the program, the exact lifetime of all the items that are stored on the stack. This constraint places limits on the flexibility of your programs, so while some Java storage exists on the stackin particular, object referencesJava objects themselves are not placed on the stack. 3)The heap. This is a

17、general-purpose pool of memory (also in the RAM area) where all Java objects live. The nice thing about the heap is that, unlike the stack, the compiler doesnt need to know how long that storage must stay on the heap. Thus, theres a great deal of flexibility in using storage on the heap. Whenever yo

18、u need an object, you simply write the code to create it by using new, and the storage is allocated on the heap when that code is executed. Of course theres a price you pay for this flexibility: It may take more time to allocate and clean up heap storage than stack storage (if you even could create

19、objects on the stack in Java, as you can in C+). 4)Constant storage.Constant values are often placed directly in the program code, which is safe since they can never change. Sometimes constants are cordoned off by themselves so that they can be optionally placed in read-only memory (ROM), in embedde

20、d systems.5)Non-RAM storage. If data lives completely outside a program, it can exist while the program is not running, outside the control of the program. The two primary examples of this are streamed objects, in which objects are turned into streams of bytes, generally to be sent to another machin

21、e, and persistent objects, in which the objects are placed on disk so they will hold their state even when the program is terminated. The trick with these types of storage is turning the objects into something that can exist on the other medium, and yet can be resurrected into a regular RAM-based ob

22、ject when necessary. Java provides support for lightweight persistence, and mechanisms such as JDBC and Hibernate provide more sophisticated support for storing and retrieving object information in databases. (2)Special case: primitive typesOne group of types, which youll use quite often in your pro

23、gramming, gets special treatment. You can think of these as “primitive” types. The reason for the special treatment is that to create an object with newespecially a small, simple variableisnt very efficient, because new places objects on the heap. For these types Java falls back on the approach take

24、n by C and C+. That is, instead of creating the variable by using new, an “automatic” variable is created that is not a reference. The variable holds the value directly, and its placed on the stack, so its much more efficient. Java determines the size of each primitive type. These sizes dont change

25、from one machine architecture to another as they do in most languages. This size invariance is one reason Java programs are more portable than programs in most other languages.(3)Arrays in JavaVirtually all programming languages support some kind of arrays. Using arrays in C and C+ is perilous becau

26、se those arrays are only blocks of memory. If a program accesses the array outside of its memory block or uses the memory before initialization (common programming errors), there will be unpredictable results. One of the primary goals of Java is safety, so many of the problems that plague programmer

27、s in C and C+ are not repeated in Java. A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The range checking comes at the price of having a small amount of memory overhead on each array as well as verifying the index at run time, but the assumption is that the

28、 safety and increased productivity are worth the expense (and Java can sometimes optimize these operations).When you create an array of objects, you are really creating an array of references, and each of those references is automatically initialized to a special value with its own keyword: null. Wh

29、en Java sees null, it recognizes that the reference in question isnt pointing to an object. You must assign an object to each reference before you use it, and if you try to use a reference thats still null, the problem will be reported at run time. Thus, typical array errors are prevented in Java. Y

30、ou can also create an array of primitives. Again, the compiler guarantees initialization because it zeroes the memory for that array. Arrays will be covered in detail in later chapters.4.You never need to destroy an objectIn most programming languages, the concept of the lifetime of a variable occup

31、ies a significant portion of the programming effort. How long does the variable last? If you are supposed to destroy it, when should you? Confusion over variable lifetimes can lead to a lot of bugs, and this section shows how Java greatly simplifies the issue by doing all the cleanup work for you.(1

32、)Scoping Most procedural languages have the concept of scope. This determines both the visibility and lifetime of the names defined within that scope. In C, C+, and Java, scope is determined by the placement of curly braces . So for example: int x = 12; / Only x available int q = 96; / Both x &

33、q available / Only x available / q is "out of scope" A variable defined within a scope is available only to the end of that scope. Any text after a / to the end of a line is a comment. Indentation makes Java code easier to read. Since Java is a free-form language, the extra spaces, tabs, a

34、nd carriage returns do not affect the resulting program. You cannot do the following, even though it is legal in C and C+: int x = 12; int x = 96; / Illegal The compiler will announce that the variable x has already been defined. Thus the C and C+ ability to “hide” a variable in a larger scope is no

35、t allowed, because the Java designers thought that it led to confusing programs.(2)Scope of objectsJava objects do not have the same lifetimes as primitives. When you create a Java object using new, it hangs around past the end of the scope. Thus if you use: String s = new String("a string"

36、;); / End of scope The reference s vanishes at the end of the scope. However, the String object that s was pointing to is still occupying memory. In this bit of code, there is no way to access the object after the end of the scope, because the only reference to it is out of scope. In later chapters

37、youll see how the reference to the object can be passed around and duplicated during the course of a program. It turns out that because objects created with new stay around for as long as you want them, a whole slew of C+ programming problems simply vanish in Java. In C+ you must not only make sure

38、that the objects stay around for as long as you need them, you must also destroy the objects when youre done with them. That brings up an interesting question. If Java leaves the objects lying around, what keeps them from filling up memory and halting your program? This is exactly the kind of proble

39、m that would occur in C+. This is where a bit of magic happens. Java has a garbage collector, which looks at all the objects that were created with new and figures out which ones are not being referenced anymore. Then it releases the memory for those objects, so the memory can be used for new object

40、s. This means that you never need to worry about reclaiming memory yourself. You simply create objects, and when you no longer need them, they will go away by themselves. This eliminates a certain class of programming problem: the so-called “memory leak,” in which a programmer forgets to release mem

41、ory.Java 編程思想作者:Bruce Eckel來源:http:/1.一切都是對象“盡管以C+為基礎,但Java是一種更純粹的面向對象程序設計語言”。無論C+還是Java都屬于雜合語言。但在Java中,設計者覺得這種雜合并不象在C+里那么重要。雜合語言允許采用多種編程風格;之所以說C+是一種雜合語言,是因為它支持與C語言的向后兼容能力。由于C+是C的一個超集,所以包含的許多特性都是后者不具備的,這些特性使C+在某些地方顯得過于復雜。Java語言首先便假定了我們只希望進行面向對象的程序設計。也就是說,正式用它設計之前,必須先將自己的思想轉入一個面向對象的世界(除非早已習慣了這個世界的思維方

42、式)。只有做好這個準備工作,與其他OOP語言相比,才能體會到Java的易學易用。在本章,我們將探討Java程序的基本組件,并體會為什么說Java乃至Java程序內的一切都是對象。2.用句柄操縱對象每種編程語言都有自己的數(shù)據(jù)處理方式。有些時候,程序員必須時刻留意準備處理的是什么類型。您曾利用一些特殊語法直接操作過對象,或處理過一些間接表示的對象嗎(C或C+里的指針)?所有這些在Java里都得到了簡化,任何東西都可看作對象。因此,我們可采用一種統(tǒng)一的語法,任何地方均可照搬不誤。但要注意,盡管將一切都“看作”對象,但操縱的標識符實際是指向一個對象的“句柄”(Handle)。在其他Java參考書里,還

43、可看到有的人將其稱作一個“引用”,甚至一個“指針”。可將這一情形想象成用遙控板(句柄)操縱電視機(對象)。只要握住這個遙控板,就相當于掌握了與電視機連接的通道。但一旦需要“換頻道”或者“關小聲音”,我們實際操縱的是遙控板(句柄),再由遙控板自己操縱電視機(對象)。如果要在房間里四處走走,并想保持對電視機的控制,那么手上拿著的是遙控板,而非電視機。此外,即使沒有電視機,遙控板亦可獨立存在。也就是說,只是由于擁有一個句柄,并不表示必須有一個對象同它連接。所以如果想容納一個詞或句子,可創(chuàng)建一個String句柄: String s;但這里創(chuàng)建的只是句柄,并不是對象。若此時向s發(fā)送一條消息,就會獲得一個

44、錯誤(運行期)。這是由于s實際并未與任何東西連接(即“沒有電視機”)。因此,一種更安全的做法是:創(chuàng)建一個句柄時,記住無論如何都進行初始化:String s = "asdf"然而,這里采用的是一種特殊類型:字串可用加引號的文字初始化。通常,必須為對象使用一種更通用的初始化類型。3.所有對象都必須創(chuàng)建創(chuàng)建句柄時,我們希望它同一個新對象連接。通常用new關鍵字達到這一目的。new的意思是:“把我變成這些對象的一種新類型”。所以在上面的例子中,可以說:String s = new String("asdf");它不僅指出“將我變成一個新字串”,也通過提供一個初始

45、字串,指出了“如何生成這個新字串”。當然,字串(String)并非唯一的類型。Java配套提供了數(shù)量眾多的現(xiàn)成類型。對我們來講,最重要的就是記住能自行創(chuàng)建類型。事實上,這應是Java程序設計的一項基本操作,是繼續(xù)本書后余部分學習的基礎。(1)保存到什么地方。程序運行時,我們最好對數(shù)據(jù)保存到什么地方做到心中有數(shù)。特別要注意的是內存的分配。有五個地方都可以保存數(shù)據(jù):1)寄存器。這是最快的保存區(qū)域,因為它位于和其他所有保存方式不同的地方:處理器內部。然而,寄存器的數(shù)量十分有限,所以寄存器是根據(jù)需要由編譯器分配。我們對此沒有直接的控制權,也不可能在自己的程序里找到寄存器存在的任何蹤跡。2)堆棧。駐留于

46、常規(guī)RAM(隨機訪問存儲器)區(qū)域,但可通過它的“堆棧指針”獲得處理的直接支持。堆棧指針若向下移,會創(chuàng)建新的內存;若向上移,則會釋放那些內存。這是一種特別快、特別有效的數(shù)據(jù)保存方式,僅次于寄存器。創(chuàng)建程序時,Java編譯器必須準確地知道堆棧內保存的所有數(shù)據(jù)的“長度”以及“存在時間”。這是由于它必須生成相應的代碼,以便向上和向下移動指針。這一限制無疑影響了程序的靈活性,所以盡管有些Java數(shù)據(jù)要保存在堆棧里特別是對象句柄,但Java對象并不放到其中。 3)堆。一種常規(guī)用途的內存池(也在RAM區(qū)域),其中保存了Java對象。和堆棧不同,“內存堆”或“堆”(Heap)最吸引人的地方在于編譯器不必知道要

47、從堆里分配多少存儲空間,也不必知道存儲的數(shù)據(jù)要在堆里停留多長的時間。因此,用堆保存數(shù)據(jù)時會得到更大的靈活性。要求創(chuàng)建一個對象時,只需用new命令編制相關的代碼即可。執(zhí)行這些代碼時,會在堆里自動進行數(shù)據(jù)的保存。當然,為達到這種靈活性,必然會付出一定的代價:在堆里分配存儲空間時會花掉更長的時間! 4)常數(shù)存儲。常數(shù)值通常直接置于程序代碼內部。這樣做是安全的,因為它們永遠都不會改變。有的常數(shù)需要嚴格地保護,所以可考慮將它們置入只讀存儲器(ROM)。 5)非RAM存儲。若數(shù)據(jù)完全獨立于一個程序之外,則程序不運行時仍可存在,并在程序的控制范圍之外。其中兩個最主要的例子便是“流式對象”和“固定對象”。對于

48、流式對象,對象會變成字節(jié)流,通常會發(fā)給另一臺機器。而對于固定對象,對象保存在磁盤中。即使程序中止運行,它們仍可保持自己的狀態(tài)不變。對于這些類型的數(shù)據(jù)存儲,一個特別有用的技巧就是它們能存在于其他媒體中。一旦需要,甚至能將它們恢復成普通的、基于RAM的對象。Java 1.1提供了對Lightweight persistence的支持。未來的版本甚至可能提供更完整的方案。(2)特殊情況:主要類型有一系列類需特別對待;可將它們想象成“基本”、“主要”或者“主”(Primitive)類型,進行程序設計時要頻繁用到它們。之所以要特別對待,是由于用new創(chuàng)建對象(特別是小的、簡單的變量)并不是非常有效,因為

49、new將對象置于“堆”里。對于這些類型,Java采納了與C和C+相同的方法。也就是說,不是用new創(chuàng)建變量,而是創(chuàng)建一個并非句柄的“自動”變量。這個變量容納了具體的值,并置于堆棧中,能夠更高效地存取。Java決定了每種主要類型的大小。就像在大多數(shù)語言里那樣,這些大小并不隨著機器結構的變化而變化。這種大小的不可更改正是Java程序具有很強移植能力的原因之一。(3)Java的數(shù)組幾乎所有程序設計語言都支持數(shù)組。在C和C+里使用數(shù)組是非常危險的,因為那些數(shù)組只是內存塊。若程序訪問自己內存塊以外的數(shù)組,或者在初始化之前使用內存(屬于常規(guī)編程錯誤),會產生不可預測的后果。Java的一項主要設計目標就是安全性。所以在C和C+里困擾程序員的許多問題都未在Java里重復。

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論