Java 简明教程

Java - Constructors

Java Constructors

*Java constructors*是 methods 的特殊类型,用于在创建 object 时初始化它。它与它的类具有相同名称,并且在语法上类似于方法。但是,构造函数没有显式返回类型。

Java constructors are special types of methods that are used to initialize an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

通常,您会使用构造函数为类定义的实例 variables 提供初始值,或执行创建完全形成的对象所需的任何其他启动过程。

Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other start-up procedures required to create a fully formed object.

所有类都有构造函数,无论您是否定义了一个,因为 Java 会自动提供一个将所有成员变量初始化为零的默认构造函数。然而,一旦您定义了自己的构造函数,默认构造函数将不再使用。

All classes have constructors, whether you define one or not because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your constructor, the default constructor is no longer used.

Rules for Creating Java Constructors

在创建 Java 构造函数时,您必须遵循以下规则:

You must follow the below-given rules while creating Java constructors:

  1. The name of the constructors must be the same as the class name.

  2. Java constructors do not have a return type. Even do not use void as a return type.

  3. There can be multiple constructors in the same class, this concept is known as constructor overloading.

  4. The access modifiers can be used with the constructors, use if you want to change the visibility/accessibility of constructors.

  5. Java provides a default constructor that is invoked during the time of object creation. If you create any type of constructor, the default constructor (provided by Java) is not invoked.

Creating a Java Constructor

要在 Java 中创建构造函数,只需编写构造函数的名称(与类名称相同),后跟括号,然后在花括号({})内编写构造函数的主体。

To create a constructor in Java, simply write the constructor’s name (that is the same as the class name) followed by the brackets and then write the constructor’s body inside the curly braces ({}).

Syntax

以下是构造函数的语法 −

Following is the syntax of a constructor −

class ClassName {
   ClassName() {
   }
}

Example to create a Java Constructor

以下示例创建了一个简单的构造函数,它将打印“Hello world”。

The following example creates a simple constructor that will print "Hello world".

public class Main {
  // Creating a constructor
  Main() {
    System.out.println("Hello, World!");
  }

  public static void main(String[] args) {
    System.out.println("The main() method.");

    // Creating a class's object
    // that will invoke the constructor
    Main obj_x = new Main();
  }
}

此程序将打印:

This program will print:

The main() method.
Hello, World!

Types of Java Constructors

Java 中有三种不同类型的构造函数,我们将其列在下面:

There are three different types of constructors in Java, we have listed them as follows:

  1. Default Constructor

  2. No-Args Constructor

  3. Parameterized Constructor

java constructors

1. Default Constructor

如果您在类中没有创建任何构造函数,Java 将提供一个初始化对象的默认构造函数。

If you do not create any constructor in the class, Java provides a default constructor that initializes the object.

在此示例中,没有我们定义的构造函数。默认构造函数用于初始化对象。

In this example, there is no constructor defined by us. The default constructor is there to initialize the object.

public class Main {
  int num1;
  int num2;

  public static void main(String[] args) {
    // We didn't created any structure
    // a default constructor will invoke here
    Main obj_x = new Main();

    // Printing the values
    System.out.println("num1 : " + obj_x.num1);
    System.out.println("num2 : " + obj_x.num2);
  }
}

Output

num1 : 0
num2 : 0

2. No-Args (No Argument) Constructor

正如名称所说明的那样,无参数构造函数不接受任何参数。通过使用无参数构造函数,您可以在对象创建时初始化类数据成员和执行您希望执行的各种活动。

As the name specifies, the No-argument constructor does not accept any argument. By using the No-Args constructor you can initialize the class data members and perform various activities that you want on object creation.

此示例创建无参数构造函数。

This example creates no-args constructor.

public class Main {
  int num1;
  int num2;

  // Creating no-args constructor
  Main() {
    num1 = -1;
    num2 = -1;
  }

  public static void main(String[] args) {
    // no-args constructor will invoke
    Main obj_x = new Main();

    // Printing the values
    System.out.println("num1 : " + obj_x.num1);
    System.out.println("num2 : " + obj_x.num2);
  }
}

Output

num1 : -1
num2 : -1

3. Parameterized Constructor

具有一个或多个参数的构造函数称为参数化构造函数。

A constructor with one or more arguments is called a parameterized constructor.

大多数情况下,您需要接受一个或多个参数的构造函数。将参数添加到构造函数中的方式与将它们添加到方法中的方式相同,只需在构造函数名称后的括号内声明它们即可。

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor’s name.

此示例创建了一个参数化构造函数。

This example creates a parameterized constructor.

public class Main {
  int num1;
  int num2;

  // Creating parameterized constructor
  Main(int a, int b) {
    num1 = a;
    num2 = b;
  }

  public static void main(String[] args) {
    // Creating two objects by passing the values
    // to initialize the attributes.
    // parameterized constructor will invoke
    Main obj_x = new Main(10, 20);
    Main obj_y = new Main(100, 200);

    // Printing the objects values
    System.out.println("obj_x");
    System.out.println("num1 : " + obj_x.num1);
    System.out.println("num2 : " + obj_x.num2);

    System.out.println("obj_y");
    System.out.println("num1 : " + obj_y.num1);
    System.out.println("num2 : " + obj_y.num2);
  }
}

Output

obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200

这里有一个使用构造函数的简单示例 −

Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
   int x;

   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}

您可以按如下方式调用构造函数来初始化对象 −

You would call constructor to initialize objects as follows −

public class ConsDemo {
   public static void main(String args[]) {
      MyClass t1 = new MyClass( 10 );
      MyClass t2 = new MyClass( 20 );
      System.out.println(t1.x + " " + t2.x);
   }
}

Output

10 20

Constructor Overloading in Java

构造函数重载表示类中有多个构造函数。当您有多个带有不同参数的构造函数时,它将称为构造函数重载。

Constructor overloading means multiple constructors in a class. When you have multiple constructors with different parameters listed, then it will be known as constructor overloading.

Example: Constructor Overloading

在此示例中,我们有一个以上的构造函数。

In this example, we have more than one constructor.

// Example of Java Constructor Overloading
// Creating a Student Class
class Student {
  String name;
  int age;

  // no-args constructor
  Student() {
    this.name = "Unknown";
    this.age = 0;
  }

  // parameterized constructor having one parameter
  Student(String name) {
    this.name = name;
    this.age = 0;
  }

  // parameterized constructor having both parameters
  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public void printDetails() {
    System.out.println("Name : " + this.name);
    System.out.println("Age : " + this.age);
  }
}

public class Main {
  public static void main(String[] args) {
    Student std1 = new Student(); // invokes no-args constructor
    Student std2 = new Student("Jordan"); // invokes parameterized constructor
    Student std3 = new Student("Paxton", 25); // invokes parameterized constructor

    // Printing details
    System.out.println("std1...");
    std1.printDetails();

    System.out.println("std2...");
    std2.printDetails();

    System.out.println("std3...");
    std3.printDetails();
  }
}

Output

td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25