代码改变世界

TIJ——Chapter Two:Everything Is an Object

2014-12-08 21:33  星星之火✨🔥  阅读(496)  评论(0编辑  收藏  举报

If we spoke a different language, we would perceive a somewhat different world.

                                     Ludwig Wittgenstein(1889-1951)

You manipulate objects with references

Although you treat everything as an object, the identifier you manipulate is actually "reference" to an object.

You must create all the objects

    |_where storage lives

It's useful to visualize some aspects of how things are laid out while the program is running—in 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 registers are allocated as they are need. You don't 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) area, but has direct support from the processor via it's 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 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 stack-in particular, object references-Java objects themselves are not placed on the stack.

3、The heap. This is a 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 doesn't need to know how long that storage must stay on the heap. Thus, there's a great deal of flexibility in using storage on the heap. Whenever you 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 there's 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 objects on the stack in Java, as you can in C++).

4、Constant storage. Constant values are often place directly in the program code, which is safe since they can never changes. Sometimes constants are cordoned off by themselves so that can be optionally placed in read-only memory(ROM), in embedded systems(An example of this is the string pool. All literal strings and string-valued constant expressions are interned automatically and put into special static storage).

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 while objects are turned into streams of bytes, generally to be sent to another machine, and persistent objects, in which the objects are placed on the disk so they will hold their state even when the program is terminated. The trick with there 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 object 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. 

简言之,栈的访问速度仅次于寄存器,Java系统必须精确的知道栈上所有东西的生命期,由于这个限制,我们仅仅把对象的引用放在栈上,而对象本身则放在堆中,这极大的增强了程序的灵活性,代价就是分配和释放存储空间比栈花费更多的时间。对于静态存储区,就是存放不能更改的常量的,比如字符串常量表达式和string字面值被自动拘留在string pool中。

    |_special case: primitive types

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 it's placed on the stack, so it's much more efficient.

Java原生数据类型表示的数据范围如下:

    |_Allays 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 safety and increased productivity are worth the expense(and Java can sometimes optimize these operations).

When you create an array of the 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.

You can also create an array of primitives. Again, the compiler guarantees initialization because it zeroes the memory for that array.

You never need to destroy an object

    |_Scoping

In C, C++, and Java, scope is determined by the placement of curly braces{}. A variable defined within a scope is available only to the end of that scope. So for example:

{
int x = 12;
// Only x available
{
int q = 96;
// Both x & q available
}
// Only x available
// q is "out of scope"
}

You cannot do the following, even though it is legal in C and C++(hide variables):

{
  int x = 12;   {     int x = 96; // illegal   } }

    |_Scope of objects

Java objects do not hava the same lifetimes as primitives. For example:

{
  String s = new String("a string");
}  // End of scope

作用域结束后,引用s消失,但是s指向的String对象任然占据内存,并且不能再访问了。直到GC(garbage collector)对其回收后,这块内存才能被其它对象使用。垃圾回收机制消除了程序员忘记释放内存造成的内存泄漏(memory leak)问题。

Creating new data types: class 

我们使用class关键字来创建一个新的类。

    |_Fields and methods

定义一个类的时候,我们可以把两种元素放在里面: fields and methods(也称成员变量和成员方法).

        |_Default values for primitive members

原声数据类型作为类的成员时,如果你不初始化,那么它就被赋一个默认的值:

Primitive type         dafult
boolean false
char '\u0000'(null)
byte (byte)0
short           (short)0
int 0
long 0L
float 0.0f
double 0.0d

The default values are only what Java guarantees when the variable is used as a member of a class. This guarantee doesn't apply to local variable. 局部变量如果不初始化,它会是一个任意的值,这种情况下使用它会引起编译期错误(很多C++编译器对于未初始化的变量只是给出警告,但是在Java中那就是一个错误,Java总是谨慎的考虑安全问题)。

Method, arguments, and return values

Methods in java determine the message an object can receive. The fundamental parts of a method are the name, the arguments, the return type, and the body. Here is the basic form:

RetruenType methodName(/* Argument list */){
  /* Method body */
}

The method name and argument list(which is called the signature of the method uniquely identify that method).

Building a Java program

    |_Name visibility

为了防止不同模块间的命名冲突,Java推荐我们将所用域名反转作为包名,这样所有的文件都有自己独一无二的命名空间,并且同一个文件中的类必须有独一无二的标识,这样就巧妙的避免了命名冲突。

    |_Using other components

倒包,使用import关键字:

import java.util.ArrayList; 告诉编译器导入ArrayList类。

import java.util.*; 导入util下的所有类。

    |_The static keyword

静态成员变量和静态方法不需要创建对象就可以使用,它们是从属于类的,被所有对象共享。

Your first Java program

下面的程序打印一行字符串,然后输出当前日期:

import java.util.*;
public class HelloDate{
  public static void main(String[] args){
    System.out.println("Hello, it's: ");
    System.out.println(new Date());
  }
}

输出如下:

Hello, it's:
Mon Dec 08 19:03:58 CST 2014

java.lang隐式地包含在每个Java源文件中。Date不在java.lang包中,因此需要显示地倒包。在JDK文档中容易得知,位于lang包下的System类有一个名为out的成员变量,它是一个static PrintStream对象。因为是静态的,因此我们不需要创建对象就可以直接使用它,我们对out对象的操作取决于它的类型: PrintStream。 看一下该类下面的方法,其中就有多个重载的println()方法供我们使用。

借助JDK文档,可以得知println(Object x)方法调用了String.valueOf(x),而valueOf(Object obj)方法调用了obj.toString(),toString()方法存在于Object方法中,Data类重写了这个方法,因此可以打印出Data对象的字符串表示。

Comments and embedded documentation

Javadoc命令将/**开头,*/结尾中间的内容写入HTML文件中,注意不要和一般的注释搞混了。利用Javadoc我们可以: Embed HTML or use "doc tags"。让我们看一个示例:

//: object/HelloDate.java
import java.util.*;

/** The first Thinking in Java example program. * Displays a string and today's date. * @author Bruce Eckel * @autonr www.MindView.net * @version 4.0 */ public class A12{   /* Entry point to class & application.    * @param args array of string arguments   * @throws exceptions No exceptions thrown   */   public static void main(String[] args){     System.out.println("Hello, it's: ");     System.out.println(new Date());   } } /* Output: (55% match) hello, it's: wed oct 05 14:39:36 MDT 2005 *///:~

Summary

The goal of this chapter is just enough Java to understand how to write a simple program. You've also gotten an overview of the language and some of it's basic ideas.

All Rights Reserved. 
Author:海峰:) 
Copyright © xp_jiang. 
转载请标明出处:http://www.cnblogs.com/xpjiang/p/4151857.html

几个生词:

perceive:觉察;理解
optimize:优化
overhead:开销