Object-Oriented-Programming Concepts in Java – Java中面向对象的编程概念

最后修改: 2019年 12月 15日

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

1. Overview

1.概述

In this article, we’ll look into Object-Oriented Programming (OOP) concepts in Java. We’ll discuss classes, objects, abstraction, encapsulation, inheritance, and polymorphism.

在这篇文章中,我们将了解Java中面向对象的编程(OOP)概念。我们将讨论类、对象、抽象、封装、继承和多态性

2. Classes

2.班级

Classes are the starting point of all objects, and we may consider them as the template for creating objects. A class would typically contain member fields, member methods, and a special constructor method.

类是所有对象的起点,我们可以将其视为创建对象的模板。一个类通常会包含成员字段、成员方法和一个特殊的构造方法。

We’ll use the constructor to create objects of the class:

我们将使用构造函数来创建该类的对象。

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

Note that a class may have more than one constructor. We can read more about the classes in our classes article.

请注意,一个类可能有不止一个构造函数。我们可以在classes文章中阅读更多关于类的信息。

3. Objects

3 对象

Objects are created from classes and are called instances of the class. We create objects from classes using their constructors:

对象是由类创建的,被称为类的实例。我们使用类的构造函数从类中创建对象。

Car veyron = new Car("Bugatti", "Veyron", "crimson");
Car corvette = new Car("Chevrolet", "Corvette", "black");

Here, we’ve created two instances of the class Car. Read more about them in our objects article.

在这里,我们创建了两个汽车类的实例。在我们的objects文章中阅读更多关于它们的信息。

4. Abstraction

4.抽象法

Abstraction is hiding complexities of implementation and exposing simpler interfaces.

抽象是隐藏复杂的实现,暴露更简单的接口。

If we think about a typical computer, one can only see the external interface, which is most essential for interacting with it, while internal chips and circuits are hidden from the user.

如果我们考虑到一台典型的计算机,人们只能看到外部界面,这对与它进行互动是最重要的,而内部的芯片和电路则对用户隐藏起来。

In OOP, abstraction means hiding the complex implementation details of a program, exposing only the API required to use the implementation. In Java, we achieve abstraction by using interfaces and abstract classes.

在OOP中,抽象意味着隐藏程序的复杂实现细节,只暴露使用实现所需的API。在Java中,我们通过使用接口和抽象类来实现抽象化。

We can read more about abstraction in our abstract class and interface articles.

我们可以在抽象类界面文章中阅读更多关于抽象的信息。

5. Encapsulation

5.封装

Encapsulation is hiding the state or internal representation of an object from the consumer of an API and providing publicly accessible methods bound to the object for read-write access. This allows for hiding specific information and controlling access to internal implementation.

封装是向API的消费者隐藏对象的状态或内部表示,并提供与该对象绑定的可公开访问的方法供读写访问。这允许隐藏特定信息并控制对内部实现的访问。

For example, member fields in a class are hidden from other classes, and they can be accessed using the member methods. One way to do this is to make all data fields private and only accessible by using the public member methods:

例如,一个类中的成员字段对其他类是隐藏的,可以使用成员方法来访问它们。一种方法是使所有的数据字段private,并且只能通过使用public成员方法来访问。

public class Car {

    // ...
    private int speed;

    public int getSpeed() {
        return color;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }
    // ...
}

Here, the field speed is encapsulated using the private access modifier, and can only be accessed using the public getSpeed() and setSpeed() methods. We can read more about access modifiers in our access modifiers article.

在这里,字段speed使用private访问修饰符进行封装,并且只能使用public getSpeed()setSpeed() 方法进行访问。我们可以在access modifiers文章中阅读更多关于访问修饰符的内容。

6. Inheritance

6.继承权

Inheritance is the mechanism that allows one class to acquire all the properties from another class by inheriting the class. We call the inheriting class a child class and the inherited class as the superclass or parent class.

继承是一种机制,它允许一个类通过继承另一个类来获得所有的属性。我们把继承的类称为子类,把继承的类称为超类或父类。

In Java, we do this by extending the parent class. Thus, the child class gets all the properties from the parent:

在Java中,我们通过扩展父类来做到这一点。因此,子类从父类获得所有的属性。

public class Car extends Vehicle { 
    //...
}

When we extend a class, we form an IS-A relationship. The Car IS-A VehicleSo, it has all the characteristics of a Vehicle.

当我们扩展一个类时,我们形成了一个IS-A关系汽车是一个车辆因此,它具有车辆的所有特性。

We may ask the question, why do we need inheritance? To answer this, let’s consider a vehicle manufacturer who manufactures different types of vehicles, such as cars, buses, trams, and trucks.

我们可能会问这样一个问题:我们为什么需要继承权?为了回答这个问题,让我们考虑一个车辆制造商,他生产不同类型的车辆,如汽车、公共汽车、电车和卡车。

To make the work easy, we can bundle the common features and properties of all vehicle types into a module (a class in case of Java). And we can let individual types inherit and reuse those properties:

为了方便工作,我们可以将所有车辆类型的共同特征和属性捆绑到一个模块中(在Java中是一个类)。而我们可以让各个类型继承和重用这些属性。

public class Vehicle {
    private int wheels;
    private String model;
    public void start() {
        // the process of starting the vehicle
    }
    
    public void stop() {
        // process to stop the vehicle
    }
    
    public void honk() { 
        // produces a default honk 
    }

}

The vehicle type Car will now inherit from the parent Vehicle class:

车辆类型Car现在将继承于父Vehicle类。

public class Car extends Vehicle {
    private int numberOfGears;

    public void openDoors() {
        // process to open the doors
    }
}

Java supports single inheritance and multilevel inheritance. This means a class cannot extend from more than one class directly, but it can use a hierarchy:

Java支持单一继承和多级继承。这意味着一个类不能直接从一个以上的类中扩展,但可以使用层次结构。

public class ArmoredCar extends Car {
    private boolean bulletProofWindows;
    
    public void remoteStartCar() {
        // this vehicle can be started by using a remote control
    }
}

Here, the ArmouredCar extends Car, and Car extends Vehicle. So, ArmouredCar inherits properties from both Car and Vehicle.

这里,ArmouredCar扩展了Car,而Car扩展了Vehicle。所以,ArmouredCarCarVehicle继承了属性。

While we inherit from the parent class, a developer could also override a method implementation from the parent. This is known as method overriding.

虽然我们继承自父类,但开发者也可以从父类中覆盖一个方法实现。这被称为method overriding

In our above example of the Vehicle class, there is the honk() method. The Car class extending the Vehicle class can override this method and implement in the way it wants to produce the honk:

在我们上面的Vehicle类的例子中,有一个honk()方法。扩展Vehicle类的Car类可以覆盖这个方法,并以它想要的方式来实现鸣笛。

public class Car extends Vehicle {  
    //...

    @Override
    public void honk() { 
        // produces car-specific honk 
    }
 }

Note that this is also termed a runtime polymorphism, as explained in the next section. We can read more about inheritance in our Java inheritance and inheritance and composition articles.

请注意,这也被称为运行时多态性,在下一节中会解释。我们可以在Java 继承继承和组合文章中阅读更多关于继承的信息。

7. Polymorphism

7.多态性

Polymorphism is the ability of an OOP language to process data differently depending on their types of inputs. In Java, this can be the same method name having different method signatures and performing different functions:

多态性是OOP语言根据其输入类型以不同方式处理数据的能力。在Java中,这可以是同一方法名称具有不同的方法签名并执行不同的功能。

public class TextFile extends GenericFile {
    //...
 
    public String read() {
        return this.getContent()
          .toString();
    }
 
    public String read(int limit) {
        return this.getContent()
          .toString()
          .substring(0, limit);
    }
 
    public String read(int start, int stop) {
        return this.getContent()
          .toString()
          .substring(start, stop);
    }
}

In this example, we can see that the method read() has three different forms with different functionalities. This type of polymorphism is static or compile-time polymorphism and is also called method overloading.

在这个例子中,我们可以看到,方法read()有三种不同的形式,具有不同的功能。这种类型的多态性是静态或编译时多态性,也被称为method overloading

There is also runtime or dynamic polymorphism, where the child class overrides the parent’s method:

还有一种运行时或动态多态性,即子类覆盖父类的方法

public class GenericFile {
    private String name;
 
    //...
 
    public String getFileInfo() {
        return "Generic File Impl";
    }
}

A child class can extend the GenericFile class and override the getFileInfo() method:

一个子类可以扩展GenericFile类并覆盖getFileInfo() 方法。

public class ImageFile extends GenericFile {
    private int height;
    private int width;
 
    //... getters and setters
     
    public String getFileInfo() {
        return "Image File Impl";
    }
}

Read more about polymorphism in our polymorphism in Java article.

在我们的Java中的多态性文章中阅读更多关于多态性的信息。

8. Conclusion

8.结语

In this article, we learned about the basic fundamental concepts of OOP with Java.

在这篇文章中,我们了解了用Java进行OOP的基本基本概念。

The code samples in this article are available over on Github.

本文中的代码样本可在Github上获得