Java Classes and Objects – Java类和对象

最后修改: 2019年 2月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll look at two basic building blocks of the Java programming language – classes and objects. They’re basic concepts of Object Oriented Programming (OOP), which we use to model real-life entities.

在这个快速教程中,我们将看看Java编程语言的两个基本构件–类和对象。它们是面向对象编程(OOP)的基本概念,我们用它来模拟现实生活中的实体。

In OOP, classes are blueprints or templates for objects. We use them to describe types of entities.

在OOP中,类是对象的蓝图或模板。我们用它们来描述实体的类型。

On the other hand, objects are living entities, created from classes. They contain certain states within their fields and present certain behaviors with their methods.

另一方面,对象是活的实体,由类创建。它们在其字段中包含某些状态,并通过其方法呈现某些行为。

2. Classes

2.班级

Simply put, a class represent a definition or a type of object. In Java, classes can contain fields, constructors, and methods.

简单地说,一个类代表一个定义或一种类型的对象。在Java中,类可以包含字段、构造函数和方法。

Let’s see an example using a simple Java class representing a Car:

让我们看一个例子,用一个简单的Java类代表一个Car

class Car {

    // fields
    String type;
    String model;
    String color;
    int speed;

    // constructor
    Car(String type, String model, String color) {
        this.type = type;
        this.model = model;
        this.color = color;
    }
    
    // methods
    int increaseSpeed(int increment) {
        this.speed = this.speed + increment;
        return this.speed;
    }
    
    // ...
}

This Java class represents a car in general. We can create any type of car from this class. We use fields to hold the state and a constructor to create objects from this class.

这个Java类代表了一般的汽车。我们可以从这个类中创建任何类型的汽车。我们用字段来保持状态,用构造函数来创建这个类的对象。

Every Java class has an empty constructor by default. We use it if we don’t provide a specific implementation as we did above. Here’s how the default constructor would look for our Car class:

每个Java类默认都有一个空的构造函数。如果我们没有像上面那样提供一个特定的实现,我们就使用它。下面是我们的Car类的默认构造函数的样子。

Car(){}

This constructor simply initializes all fields of the object with their default values. Strings are initialized to null and integers to zero.

该构造函数简单地将对象的所有字段初始化为其默认值。字符串被初始化为null,整数被初始化为0。

Now, our class has a specific constructor because we want our objects to have their fields defined when we create them:

现在,我们的类有一个特定的构造函数,因为我们希望我们的对象在创建时有其字段的定义。

Car(String type, String model) {
    // ...
}

To sum up, we wrote a class that defines a car. Its properties are described by fields, which contain the state of objects of the class, and its behavior is described using methods.

总而言之,我们写了一个定义汽车的类。它的属性由字段描述,字段包含了该类对象的状态,而它的行为则由方法描述。

3. Objects

3.物体

While classes are translated during compile time, objects are created from classes at runtime.

虽然类是在编译时翻译的,但对象是在运行时由类创建的

Objects of a class are called instances, and we create and initialize them with constructors:

一个类的对象被称为实例,我们用构造函数创建并初始化它们。

Car focus = new Car("Ford", "Focus", "red");
Car auris = new Car("Toyota", "Auris", "blue");
Car golf = new Car("Volkswagen", "Golf", "green");

Now, we’ve created different Car objects, all from a single class. This is the point of it all, to define the blueprint in one place, and then, to reuse it many times in many places.

现在,我们已经创建了不同的汽车对象,都来自一个单一的类。这就是这一切的重点,在一个地方定义蓝图,然后,在许多地方多次重复使用它。

So far, we have three Car objects, and they’re all parked since their speed is zero. We can change this by invoking our increaseSpeed method:

到目前为止,我们有三个汽车对象,它们都在停车,因为它们的速度是零。我们可以通过调用我们的increaseSpeed方法来改变这种情况。

focus.increaseSpeed(10);
auris.increaseSpeed(20);
golf.increaseSpeed(30);

Now, we’ve changed the state of our cars – they’re all moving at different speeds.

现在,我们已经改变了汽车的状态–它们都在以不同的速度行驶。

Furthermore, we can and should define access control to our class, its constructors, fields, and methods. We can do so by using access modifiers, as we’ll see in the next section.

此外,我们可以而且应该定义对我们的类、其构造函数、字段和方法的访问控制。我们可以通过使用访问修饰符来做到这一点,我们将在下一节看到。

4. Access Modifiers

4.访问修改器

In the previous examples, we omitted access modifiers to simplify the code. By doing so, we actually used a default package-private modifier. That modifier allows access to the class from any other class in the same package.

在前面的例子中,我们省略了访问修饰符来简化代码。通过这样做,我们实际上使用了一个默认的包-私有修改器。该修饰符允许从同一包中的任何其他类中访问该类。

Usually, we’d use a public modifier for constructors to allow access from all other objects:

通常,我们会对构造函数使用public修饰符,以允许所有其他对象的访问。

public Car(String type, String model, String color) {
    // ...
}

Every field and method in our class should’ve also defined access control by a specific modifier. Classes usually have public modifiers, but we tend to keep our fields private.

我们类中的每个字段和方法都应该通过一个特定的修饰符来定义访问控制。类通常有public修改器,但我们倾向于保持我们的字段private

Fields hold the state of our object, therefore we want to control access to that state. We can keep some of them private, and others public. We achieve this with specific methods called getters and setters.

字段持有我们对象的状态,因此我们要控制对该状态的访问。我们可以让其中一些字段保持private,而其他字段保持public。我们通过被称为getters和setters的特定方法来实现这一点。

Let’s have a look at our class with fully-specified access control:

让我们来看看我们的具有完全指定的访问控制的类。

public class Car {
    private String type;
    // ...

    public Car(String type, String model, String color) {
       // ...
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getSpeed() {
        return speed;
    }

    // ...
}

Our class is marked public, which means we can use it in any package. Also, the constructor is public, which means we can create an object from this class inside any other object.

我们的类被标记为public,这意味着我们可以在任何包中使用它。而且,构造函数是public,这意味着我们可以在任何其他对象中从这个类创建一个对象。

Our fields are marked private, which means they’re not accessible from our object directly, but we provide access to them through getters and setters.

我们的字段被标记为private,这意味着它们不能从我们的对象中直接访问,但我们通过getters和setters提供对它们的访问。

The type and model fields do not have getters and setters, because they hold internal data of our objects. We can define them only through the constructor during initialization.

typemodel字段没有getters和setters,因为它们持有我们对象的内部数据。我们只能在初始化时通过构造函数来定义它们。

Furthermore, the color can be accessed and changed, whereas speed can only be accessed, but not changed. We enforced speed adjustments through specialized public methods increaseSpeed() and decreaseSpeed().

此外,color可以被访问和改变,而speed只能被访问,但不能改变。我们通过专门的public方法increaseSpeed()decreaseSpeed()来强制调整速度。

In other words, we use access control to encapsulate the state of the object.

换句话说,我们使用访问控制来封装对象的状态。

5. Conclusion

5.结论

In this article, we went through two basic elements of the Java language, classes, and objects, and showed how and why they are used. We also introduced the basics of access control and demonstrated its usage.

在这篇文章中,我们经历了Java语言的两个基本元素,类和对象,并展示了它们的使用方法和原因。我们还介绍了访问控制的基础知识,并演示了其用法。

To learn other concepts of Java language, we suggest reading about inheritance, the super keyword, and abstract classes as a next step.

要学习Java语言的其他概念,我们建议下一步阅读继承超级关键字抽象类等内容。

The complete source code for the example is available over on GitHub.

该示例的完整源代码可在GitHub上找到