Documentation

The Java™ Tutorials
Hide TOC
Variables变量
Trail: Learning the Java Language
Lesson: Language Basics

Variables变量

As you learned in the previous lesson, an object stores its state in fields.如前一课所述,对象将其状态存储在字段中。

int cadence = 0;
int speed = 0;
int gear = 1;

The What Is an Object? discussion introduced you to fields, but you probably have still a few questions, such as: What are the rules and conventions for naming a field?什么是对象?的讨论向您介绍了字段,但您可能还有一些问题,例如:命名字段的规则和约定是什么?Besides int, what other data types are there? Do fields have to be initialized when they are declared?除了int,还有哪些其他数据类型?声明字段时是否必须初始化字段?Are fields assigned a default value if they are not explicitly initialized?如果字段未显式初始化,是否为其指定了默认值?We'll explore the answers to such questions in this lesson, but before we do, there are a few technical distinctions you must first become aware of.在本课中,我们将探讨这些问题的答案,但在此之前,您必须首先了解一些技术区别。In the Java programming language, the terms "field" and "variable" are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing.在Java编程语言中,术语“字段”和“变量”都被使用;这在新开发人员中是一个常见的混淆源,因为两者似乎经常提到同一件事。

The Java programming language defines the following kinds of variables:Java编程语言定义了以下类型的变量:

Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields and variables.话虽如此,本教程的其余部分在讨论字段和变量时使用以下一般准则。If we are talking about "fields in general" (excluding local variables and parameters), we may simply say "fields".如果我们谈论的是“一般字段”(不包括局部变量和参数),我们可以简单地说“字段”。If the discussion applies to "all of the above", we may simply say "variables".如果讨论适用于“上述所有”,我们可以简单地说“变量”。If the context calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate.如果上下文需要区分,我们将酌情使用特定术语(静态字段、局部变量等)。You may also occasionally see the term "member" used as well.您偶尔也会看到使用“成员”一词。A type's fields, methods, and nested types are collectively called its members.类型的字段、方法和嵌套类型统称为其成员。

Naming命名

Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different.对于允许使用的名称类型,每种编程语言都有自己的规则和约定,Java编程语言也不例外。The rules and conventions for naming your variables can be summarized as follows:命名变量的规则和约定可总结如下:


Previous page: Language Basics
Next page: Primitive Data Types