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:开销

TIJ——Chapter Two:Everything Is an Object的更多相关文章

  1. TIJ——Chapter One:Introduction to Objects

    ///:~容我对这个系列美其名曰"读书笔记",其实shi在练习英文哈:-) Introduction to Objects Object-oriented programming( ...

  2. TIJ——Chapter Twelve:Error Handling with Exception

    Exception guidelines Use exceptions to: Handle problems at the appropriate level.(Avoid catching exc ...

  3. TIJ——Chapter Eleven:Holding Your Objects

    Java Provides a number of ways to hold objects: An array associates numerical indexes to objects. It ...

  4. TIJ——Chapter Eight:Polymorphism

    The twist |_Method-call binding Connecting a method call to a method body is called binding. When bi ...

  5. TIJ——Chapter Seven:Reusing Classes

    Reusing Classes 有两种常用方式实现类的重用,组件(在新类中创建存在类的对象)和继承. Composition syntax Every non-primitive object has ...

  6. TIJ——Chapter Five:Initialization & Cleanup

    Method overloading |_Distinguishing overloaded methods If the methods hava the same name, how can Ja ...

  7. Chapter 3 Discovering Classes and Object

    Chatper 3 Discovering Classes and Object Exercises: 1.What is a class? A class is a template for man ...

  8. TIJ——Chapter Fourteen:Type Information

    Runtime type information(RTTI) allows you to discover and use type information while a program is ru ...

  9. TIJ——Chapter Thirteen:Strings

    String 对象是不可修改的,对于被String 重载的'+' 和'+=' 运算符来说,当你用它们来连接两个String 对象的时候,它在底层并不会对于每一次连接均生成一个String 对象,取而代 ...

随机推荐

  1. a single statement, not multiple statements

    http://dev.mysql.com/doc/refman/5.7/en/prepare.html Statement names are not case sensitive. preparab ...

  2. 1Web语言:开始了解HTML

    HTML是hybertext markup language的缩写,用来告诉浏览器网页的结构和内容.HTML的所有工作都是关于结构的,而不是外观.CSS是级联样式表(Cascading Style S ...

  3. AndEngine

    AndEngine http://www.oschina.net/question/54100_16765

  4. C#委托初探

    委托是一种定义方法签名的类型,可以与具有兼容签名的任何方法关联.您可以通过委托调用其中已添加的方法列表.委托用于将方法作为参数传递给其他方法.事件处理程序就是通过委托调用的方法.您可以创建一个自定义方 ...

  5. git-svn

    sudo apt-get install git-svn svn作为一个优秀源码版本的管理工具,可以适合绝大多数项目.但是因为它的采用中心化管理,不可避免的存在本地代码的备份和版本管理问题.也就是说对 ...

  6. C# json object互转工具

    public static T Deserializer<T>(string path) { try { System.Xml.XmlDocument xd = new System.Xm ...

  7. 为mutable类型的容器(array,set等)添加kvo,有点麻烦,供参考和了解下吧

    http://blog.csdn.net/caryaliu/article/details/49284185 需要在被观察的属性所在的类里面实现一些方法,对开发者不友好,一般不建议使用,这里mark一 ...

  8. HBASE的读写以及client API

    一:读写思想 1.系统表 hbase:namespace 存储hbase中所有的namespace的信息 hbase:meta rowkey:hbase中所有表的region的名称 column:re ...

  9. Qt操作Oracle

    很久以前写过<Qt数据库操作>的一篇文章,在操作数据库的时候,温习了一下!感觉很好!但在操作Oracle数据库时又遇到了一些问题.在使用QSqlRelationalTableModel操纵 ...

  10. DPM总结

    DPM:Deformable Parts Model(来自http://www.cs.berkeley.edu/~rbg/latent/index.html) 目标检测算法 先计算梯度方向直方图,在用 ...