1 module and class、object
A vital idea in programming (and perhaps in all of science and math) is how large things are built of ***aller things, and how those large things are used to build even larger things.
在编程(也许在所有科学和数学领域)中,一个至关重要的想法是,大的东西是如何由小的东西构成的,以及这些大的东西是如何被用来构建更大的东西的。
The classic example is Lego bricks, where individual bricks are used to build larger assemblies which in turn are used to build even larger assemblies, which are used to build even larger constructions.
经典的例子是乐高积木,单个积木被用来建造更大的组件,而这些组件又被用来建造更大的组件,这些组件被用来建造更大的建筑。
In geometry, Euclid's axioms are the basic bricks, which are used to build basic theorems, which in turn are used to build more theorems, which are used to build even more advanced theorems. Over the years, a very large structure has been built out of the fundamental axioms. (And the building continues to this day.)
在几何学中,欧几里德公理是基本的砖块,用来建立基本的定理,反过来又用来建立更多的定理,这些定理被用来建立更高级的定理。多年来,一个非常大的结构已经建立了基本的公理。(这栋建筑一直延续到今天。)
In programming, this idea is called modularity. A module encapsulates some well-defined functions and data and is used as a brick to build even larger modules. We have already seen this with expressions built out of operands and operators, statements built out of expressions, statements put into larger groups to make programs.
在编程中,这种想法被称为模块化。模块封装了一些定义良好的函数和数据,并用作构建更大模块的砖块。我们已经看到了由操作数和运算符构建的表达式、由表达式构建的语句、放入更大组件以生成程序。
Industrial-strength programs can be very large. A modern operating system can be 10s of millions of lines of code. This would be impossible to create without the idea of dividing it into thousands of individual modules.
工业级的程序可能非常庞大。一个现代的操作系统可以有上千万行代码。如果没有将其划分为数千个单独模块的想法,这是不可能实现的。
In object oriented programming, the idea of modularity is implemented with objects. An object contains both data and methods and can be used like a brick to build larger objects.
在面向对象编程中,模块化的思想是用对象实现的。对象包含数据和 *** ,可以像砖块一样用于构建更大的对象。
A primitive data type uses a ***all amount of memory to represent a single item of data. All data of the same primitive type are the same size.
基本数据类型使用少量内存来表示单个数据项。相同基本类型的所有数据大小相同。
For example, primitive type int represents integers using 32 bits. All variables of type int use 32 bits.
例如,基本类型int使用32位表示整数。int类型的所有变量都使用32位。
There are only eight primitive data types in Java: byte, short, int, long, float, double, char, and boolean. A Java program cannot define any other primitive data types.
Java中只有八种基本数据类型:字节、短整形、整型、长整型、浮点型、双精度型、字符型和布尔型。Java程序不能定义任何其他基本数据类型。
An object is a large chunk of memory that can potentially contain a great deal of data along with methods (little programs) to process that data.
对象是一大块内存,可能包含大量数据以及处理这些数据的 *** (小程序)。
There are thousands of object classes that come standard with Java, and a programmer can easily create additional classes.
Java标准提供了数千个对象类,程序员可以轻松创建其他类。
An object consists of both data and methods.
对象由数据和 *** 组成。
The picture illustrates a conceptual object. The little yellow bricks represent bytes of memory. The methods of the object and the data of the object are constructed out of bytes. This object contains the characters "Elementary, my dear Watson!" and contains several methods to manipulate that data.
这幅画描绘了一个概念性的物体。小黄砖代表字节的内存。对象的 *** 和对象的数据是用字节构造的。此对象包含字符“Elementary, my dear Watson!”并包含了几种处理这些数据的 *** 。(The objects have identity, is a distinct block of memory and state(instance varialbe), behavior(method).)
A class is a description of a kind of object.
类是一种对象的描述。
A class is the data type of that kind of object. A class describes what an object of a particular type is made of, its data and its methods. A class is merely a description. It is like a plan for building a house. Before you build a house, you should have a plan. Once you have a plan, however, you can build any number of houses that follow that plan.
类是这种对象的数据类型。类描述特定类型的对象的组成、数据和 *** 。类仅仅是一种描述。这就像一个建造房屋的计划。在你盖房子之前,你应该有一个计划。然而,一旦你有了一个计划,你就可以按照这个计划建造任意数量的房屋。
2 Creating an Object
demo code:
public class StringDemo1 { public static void main ( String[] args ) { String str ; // creates a reference variable, but does not create a String object. // The variable str is used to refer to a String after one has been created. str = new String( "Elementary, my dear Watson!" ); // creates an object and puts a reference to that object in str. } }
The new operator asks for an object to be constructed. The Java virtual computer creates an object by following the description contained in its class.
new操作符要求构造一个对象。Java虚拟计算机通过遵循其类中包含的描述来创建对象。
The example program creates a String object. When the program runs, the expression
示例程序创建一个字符串对象。当程序运行时,表达式
new String( "Elementary, my dear Watson!" )
creates a new String object by following the description contained in the String class. This description is contained in a standard software package that comes with Java. The particular object created in this case contains characters "Elementary, my dear Watson!". The new object contains all the methods and features that are described in the String class.
按照String类中包含的描述创建新的String对象。该描述包含在Java附带的标准软件包中。本例中创建的特定对象包含字符“Elementary,my dear Watson!”。新对象包含String类中描述的所有 *** 和功能。
All objects of the same class contain the same methods. All objects of the same class contain the same types of data although the values of the data will be different from object to object. For example, all String objects contain the same methods. All String objects contain a string of characters, but the characters will be different from object to object.
同一类的所有对象都包含相同的 *** 。同一类的所有对象都包含相同类型的数据,尽管不同对象的数据值不同。例如,所有字符串对象都包含相同的 *** 。所有字符串对象都包含一个字符串,但每个对象的字符都不同。
The program could now use the methods of this object to do some things with the characters. However, this program does nothing further. After the program stops running, the object no longer exists. The memory out of which it was made can now be used for other purposes.
程序现在可以使用这个对象的 *** 来处理字符。然而,这个程序没有进一步的作用。程序停止运行后,对象不再存在。创建它的内存现在可以用于其他目的。
Here is the assignment statement we are considering:
以下是我们正在考虑的表达式语句:
str = new String( "Elementary, my dear Watson!" );
It works like this:
(1) Evaluate the expression 计算表达式
The expression
new String( "Elementary, my dear Watson!" )
is evaluated. This constructs (creates) a new object. The value of this expression is a reference to the new object.
进行了计算。这将构造(创建)一个新对象。此表达式的值是对新对象的引用。
A constructor for an object has the same name as the class and is used with the new operator. Sometimes (as in this example) a constructor requires parameters.
对象的构造函数与类同名,并与新运算符一起使用。有时(如本例中)构造函数需要参数。
A constructor returns a reference to the object it has created. A reference to an object describes its location in memory. It enables the Java virtual computer to find the object.
构造函数返回对其创建的对象的引用。对对象的引用描述了它在内存中的位置。它使Java虚拟计算机能够找到对象。
(2) Store the value in the variable 将值存储在变量中
In the second step, the reference (the value) is stored in the reference variable:
在第二步中,参考(值)存储在参考变量中:
str = The reference to the string just created
str=对刚刚创建的字符串的引用
Now whenever the program needs to refer to the object it uses the variable str.
现在,只要程序需要引用对象,它就会使用变量str。
A reference is like a cell phone number. Someone who has your number can send you a message, and ask you to do something, no matter where you are. Think of your boss calling you and sending a message, "Start working on that report!" This is like using an object reference to ask the object to run a method.
引用就像一个手机号码。有你 *** 号码的人可以给你发个信息,让你做点什么,不管你在哪里。想象一下,你的老板打 *** 给你,给你发了一条信息,“开始写那份报告!”这类似于使用对象引用要求对象运行 *** 。
Sometimes the variable str is called the "name" of the object. This is a simplification and can lead to confusion if you are not careful. The object, the reference variable, and the reference are three different things.
有时变量str被称为对象的“名称”。这是一种简化,如果不小心,可能会导致混淆。对象、引用变量和引用是三个不同的东西。
Objects and references to objects are very common in the real world. But sometimes the distinction between objects and object references is hard to see in a program. Here is an ***ogy that may help:
对象和对对象的引用在现实世界中非常常见。但有时在程序中很难看到对象和对象引用之间的区别。以下是一个可能有帮助的类比:
object you reference your cell phone number reference a slip of paper with your cell phone number on it, variable held by someone who wants to send messages to you
The picture on the below shows the program after the assignment statement has run. The reference is shown as an arrow that leads to the object, and this is a good way to think of it. (Although in reality it is just a bit pattern, like everything else in computer memory.)
下边的图片显示了赋值语句运行后的程序。引用显示为指向对象的箭头,这是一种很好的思考方式。(尽管在现实中,它只是一种比特模式,就像计算机内存中的其他东西一样。)
The variable will continue to hold the reference to the object until some other assignment statement changes it or the program ends.
变量将继续保持对对象的引用,直到其他赋值语句更改它或程序结束。
2 基础类型和引用类型
All data in Java falls into one of two categories: primitive data and objects. Objects(located at heap) are refered by reference variable(located at stack).
primitive variable
reference variable
Information it Contains
Contains actual data.
Contains information on how to find an object (a reference).
When on the left of =
Previous data is replaced with new data.
Old reference is replaced with a new reference
What's in It
Fixed number of bits. Contains the actual data.
Contains information on how to find the object.
When used in an expression:
Use the data in the variable.
Use the reference in the variable to find the object.
For primitive types, also, the == operator looks only at the variables.
此外,对于基础类型,==运算符只查看变量。
The contents of the variables x and y are examined. But with primitive types, the contents of a variable is the data, so with primitive types == looks at data.
检查变量x和y的内容。但对于基础类型,变量的内容是数据,因此对于基础类型操作符==可 以查看数据。
With reference types, == looks at the contents of the variables, but the variables contain object references.
对于引用类型,==查看变量的内容,但变量包含对象引用。
The equals( String ) method of class String tests if two Strings contain the same characters in the same sequence.
类String的equals *** 测试两个字符串是否在同一序列中包含相同的字符。
Strings are common in programs, so Java optimizes their use. Usually if you need a string in your program you create it as follows. Notice that new is not used:
字符串在程序中很常见,所以Java优化了它们的使用。通常,如果你的程序中需要一个字符串,你可以按如下方式创建它。请注意,不使用new:
String str = "String Literal" ;
This creates a string literal that contains the characters "String Literal". A string literal is an object of class String. The compiler keeps track of the literals in your program and will reuse the same object when it can. (The compiler will not try to reuse other types of objects. String literals are special.)
这将创建一个包含字符“string literal”的字符串文字。字符串文字是string类的对象。编译器会跟踪程序中的文本,并在可能的情况下重用同一对象。(编译器不会尝试重用其他类型的对象。字符串文字是特殊的,作为常量放在常量池中。)
For example, say that a program contained the following statements:
例如,假设一个程序包含以下语句:
String str1, str2; str1 = "String Literal" ; str2 = "String Literal" ;
Only one object is created, containing the characters "String Literal". This is safe, because strings are immutable, so the object str1 refers to will not change, and the object str2 refers to will not change, so if the data is always the same, only one object is needed to contain it. There is no need for two string objects whose content is equivalent.
只创建一个对象,包含字符“String Literal”。这是安全的,因为字符串是不可变的,所以str1引用的对象不会更改,str2引用的对象不会更改,所以如果数据总是相同的,则只需要一个对象来包含它。不需要两个内容等效的字符串对象。
Here is different situation:
以下是不同的情况:
String strA, strB; strA = new String("My String") ; strB = new String("My String") ;
Now two objects are created, containing equivalent data. The compiler does not reuse the first object.
现在创建了两个对象,其中包含等效的数据。编译器不会重用之一个对象。
It is assumed that because you explicitly used two new commands that you really want two separate objects.
假设因为显式使用了两个新命令,所以确实需要两个单独的对象。
Sometimes your data is an int, a primitive, but you need the data in an object.
有时,数据是一个int,一个基础类型,但您需要对象中的数据。
For example, a method might require an object for a parameter, but what you have is an int.
例如,一个 *** 可能需要一个对象作为参数,但您拥有的是一个int。
There is a division between primitive data and objects. The division sometimes needs to be crossed.
在原始数据和对象之间有一个划分。有时需要跨越分歧。
For each primitive type, there is a corresponding wrapper class.
对于每个基本类型,都有一个对应的包装器类。
A wrapper class is used to put primitive data value into an object. Think of wrapping up the data with an object, like wrapping up a gift.
包装器类用于将原始数据值放入对象中。想象一下用一个对象包装数据,就像包装礼物一样。
Wrapper classes can also go the other direction. Objects (of a wrapper class) can be converted into primitive data. The table shows primitive types and their wrapper classes. Java is case sensitive, so byte and Byte are different types.
包装器类也可以向另一个方向发展。(包装类的)对象可以转换为原始数据。下表显示了基本类型及其包装类。Java区分大小写,所以字节和字节是不同的类型。
primitive type
Wrapper type
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
As an example, the value 103 could be held in 32 bit section of memory that is of primitive data type int. The same value could be held in an object that is of type Integer. The object will use many more than 32 bits.
例如,值103可以保存在原始数据类型int的32位内存段中。相同的值可以保存在类型Integer的对象中。该对象将使用超过32位的数据。
The wrapper classes are defined in the package java.lang and so (like all classes in that package) are automatically available to your programs.
包装器类定义在java.lang中,该包(与该包中的所有类一样)可自动可用于您的程序。
3 Running a non-static Method
Here is the example program, now with additional statements:
public class StringDemo2 { public static void main ( String[] args ) { String str; int len; str = new String( "Elementary, my dear Watson!" ); len = str.length(); // call the length() method of the object System.out.println("The length is: " + len ); } }
The expression
str.length();
runs the length() method of the object referred to by str. This method counts the number of characters in the data of the object. In our object, it counts the number of characters in "Elementary, my dear Watson!" which is 27. That value is then assigned to the int variable len. Space characters and punctuation characters are included in the length of a string.
运行str引用的对象的length() *** 。此 *** 统计对象数据中的字符数。在我们的对象中,它计算“Elementary, my dear Watson!”字符数量27。然后将该值分配给int变量len。字符串的长度中包含空格字符和标点字符。
Calling a method means asking a method to run. This program called the length() method. (Sometimes the phrase invoking a method is used to mean the same thing.)
调用一个 *** (Calling a method)意味着要求一个 *** 运行。这个程序称为length() *** 。(有时,invoking a method的短语用于表示相同的意思。)
Methods frequently return a value. The length method returned the value 27. (Sometimes a method is said to evaluate to a value.) It is as if the method call is replaced by the value it returns. So that
*** 经常返回一个值。length *** 返回值27。(有时一种 *** 被称为计算一个值。)就像 *** 调用被它返回的值替换一样。因此
len = str.length();
is replaced with
被替换为
len = 27;
4 Running a static Method
The methods that belong to a class definition are called static methods. (Sometimes they are called class methods, but this is confusing.) A static method is part of a class definition, but is not part of the objects it creates.
属于类定义的 *** 称为静态 *** 。(有时它们被称为类 *** ,但这令人困惑。)静态 *** 是类定义的一部分,但不是它创建的对象的一部分。
A program can execute a static method without first creating an object! All other methods (those that are not static) exist only when they are part of an object. So an object must be created before they can be executed.
程序可以执行静态 *** ,而无需先创建对象!所有其他 *** (非静态 *** )仅当它们是对象的一部分时才存在。因此,必须先创建一个对象,然后才能执行它们。
(非静态 *** 有一个隐式的指向对象的引用,而静态 *** 没有,也不需要。)
5 Composition (Objects that Contain Objects)
class Jam { // Instance Variables private String contents ; // type of fruit in the jar private String date ; // date of canning private int capacity ; // amount of jam in the jar // Constructors public Jam( String contents, String date, int size ) { this . contents = contents ; this . date = date ; capacity = size; } // Methods public boolean empty () { return ( capacity== 0 ) ; } public String toString() { return contents + " " + date + " " + capacity + " fl. oz." ; } public void spread ( int fluidOz ) { if( !empty() ) { if( fluidOz <= capacity ) { System.out.println("Spreading " + fluidOz + " fluid ounces of " + contents ); capacity = capacity - fluidOz ; } else { System.out.println("Spreading " + capacity + " fluid ounces of " + contents ); capacity = 0 ; } } else System.out.println("No jam in the Jar!"); } } class Pantry { // Instance Variables private Jam jar1 ; private Jam jar2 ; private Jam jar3 ; private Jam selected ; // Constructors Pantry( Jam jar1, Jam jar2, Jam jar3 ) { this . jar1 = jar1 ; this . jar2 = jar2 ; this . jar3 = jar3 ; selected = null ; } // Methods public String toString() { String str = ""; str += "1: " + jar1.toString() + "\n"; str += "2: " + jar1.toString() + "\n"; str += "3: " + jar1.toString() + "\n"; return str; } // assume that the user entered a correct selection, 1, 2, or 3 public void select( int jarNumber ) { if( jarNumber == 1 ) selected = jar1 ; else if( jarNumber == 2 ) selected = jar2 ; else selected = jar3 ; } // spread the selected jam public void spread( int oz ) { selected . spread( oz ) ; } } public class PantryTester { public static void main ( String[] args ) { Jam goose = new Jam( "Gooseberry", "7/4/86", 12 ); Jam apple = new Jam( "Crab Apple", "9/30/99", 8 ); Jam rhub = new Jam( "Rhubarb", "10/31/99", 3 ); Pantry hubbard = new Pantry( goose, apple, rhub ); System.out.println( hubbard ); hubbard.select(1); hubbard.spread(2); System.out.println( hubbard ); hubbard.select(3); hubbard.spread(4); System.out.println( hubbard ); } }
6 Packages 包
A group of related classes is often put into a collection called a package.
一组相关的类通常被放入称为包的***中。
Many packages come standard with Java. For example, the String class is part of the package called java.lang. Several useful classes are part of that package. You can use the classes in this package without doing anything special.
许多软件包都是Java的标准配置。例如,String类是名为java的包的一部分。几个有用的类是这个包的一部分。您可以使用这个包中的类,而无需做任何特殊的操作。
Other standard packages also come with Java. To use a class from one of these packages your program must tell the compiler what package contains the class. One way to do this is to use the package name with the class. Here is a program that explicitly mentions where the String class is found:
Java还附带了其他标准包。要使用其中一个包中的类,程序必须告诉编译器该类包含在哪个包中。一种 *** 是在类中使用包名。下面是一个程序,它明确提到了字符串类的位置:
public class ImportDemo01 { public static void main ( String[] args ) { java.lang.String str; int len; str = new java.lang.String( "Elementary, my dear Watson!" ); len = str.length(); System.out.println("The length is: " + len ); } }
This program works the same way as the previous version. The package java.lang does not need to be explicitly mentioned when you need to use String, although it does not hurt to do so.
此程序的工作方式与上一版本相同。这个包是java的。当您需要使用字符串时,不需要显式地提到lang,尽管这样做并没有坏处。
The compiler is told that the class Scanner is in the package java.util:
import java.util.Scanner; // Importing Scanner class in java.util package //import java.util.*; // importing all classes in a package public class ImportDemo03 { public static void main ( String[] args ) { Scanner scan ; scan = new Scanner( System.in ); // do something with the Scanner object (see next chapter) } }
包与文件夹,类与文件:
“之一个事实。Java 程序由类组成。每个类都存储在一个单独的文件中,其文件名称与类名一致。该文件的扩展名为 java。”
“所以,一个程序由一系列带有‘java’文件扩展名的文件组成,每个文件只包含一个类的代码,对吗?”
“完全正确,阿米戈。如果一个文件名为 MyCat.java,则它包含 MyCat 类。”
“第二个事实。当我们有许多类文件时,我们会将它们分组到文件夹和子文件夹中。此外,类还会被分组到包和子包中。包和子包的名称必须在类代码中指定,并且这些名称必须与驱动器上的文件夹和子文件夹名称相同。”
“因此,一方面,我们把文件存储在文件夹中,另一方面,类被存储在包中。一个类名还必须与描述该类的文件的名称一致。包名称要与存储该类的文件夹的名称一致。”
“你能告诉我更多细节吗?”
“嵌套包的名称用句点分隔,类似于一个链接。”
“换句话说,假设你有一个名为 Cat 的类,存储在 animals.pets 包中。这意味着:
硬盘中存在一些文件夹(我们称之为 src),其中存储了所有项目文件。
其中包含一个名为 animals 的文件夹,而该文件夹又包含一个名为 pets 的子文件夹。
该 pets 文件夹包含一个 Cat.java 文件,该文件又包含 Cat 类的代码。”
“我不太明白你的意思。”
“是这样的。类和包的结构反映了驱动器上文件夹和文件的结构。如果我们有一个名为 House.java 的文件,其存储在 src/com/houses 文件夹中, 那么就存在一个名为 House 的类,其存储在 com.houses 包中。”
ref:
http://www.programmedlessons.org/Java9/index.html
-End-