首页 > 代码库 > Chapter 3 Introduction to Objects and Input/Output
Chapter 3 Introduction to Objects and Input/Output
与声明一个primitive variable不同,声明一个对象的时候,并不创建用来存储一个对象的内存空间,而是创建了一个存储该对象所在内存空间的地址。
在java里,new是一个操作符,它让系统分配一个特定类型的存储空间,并返回该内存空间的地址。
String str;
str = “Java Programing”;
和
String str = new String("Java Programing");
是有区别的,前者是把已经存在的“Java Programming”的存储地点赋值给str,而后在,需要先生存一个"Java Programing",然后再把它的地址赋值给str。
In reality, when the statement in Line 4 executes, it first looks if the program
has already created the string "Java Programming". If this is the case, then the
String variable str will point to that memory location. However, when the statement
in Line 5 executes, the system will allocate a memory space, store the string "Java
Programming" into that memory space, and then store the address of that memory
space into str. This is a key difference and plays an important role when strings and
String variables are compared, which we will explain in Chapter 4.
In Java, variables such as str are called reference variables. More formally, reference
variables are variables that store the address of a memory space. In Java, any variable
declared using a class (such as the variable str) is a reference variable. Because str is a
reference variable declared using the class String, we say that str is a reference
variable of the String type.
Primitive type variables store data directly into their own memory spaces. Reference
variables store the address of the object containing the data. An object is an instance of
a class and the operator new is used to instantiate an object. In some languages, such as
C++, reference variables are called pointers.
Before discussing the class String, we first discuss how to use predefined methods in a
program.
There are two types of methods in a class: static and non-static. A static
method can be used, that is, called, using the name of the class containing the method.
static修饰的method,可以直接用类名来调用它,比如Math.pow(2,3)。
129页,输入输出
Chapter 3 Introduction to Objects and Input/Output