java构造方法_Java构造方法

java构造方法

A Java constructor creates a new instance of an already-defined object. This article discusses how to use Java constructor methods to create a Person object.

Java构造函数创建一个已定义对象的新实例。 本文讨论如何使用Java构造方法创建Person对象。

Note: You need to create two files in the same folder for this example: Person.java defines the Person class, and PersonExample.java contains the main method that creates Person objects.

注意:对于本示例,您需要在同一文件夹中创建两个文件: Person.java定义Person类,而PersonExample.java包含创建Person对象的主要方法

构造方法 ( The Constructor Method )

Let's start by creating a Person class that has four private fields: firstName, lastName, address, and username. These fields are private variables and together their values make up the state of an object. We've also added the simplest of constructor methods:

让我们开始创建一个Person类,该类具有四个私有字段:firstName,lastName,address和username。 这些字段是私有变量,它们的值共同构成对象的状态。 我们还添加了最简单的构造方法:

 public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
//The constructor method
public Person()
{
}
}

The constructor method is similar to any other public method except that it shares the same name as the class, and it cannot return a value. It can have none, one or many parameters.

构造函数方法与任何其他公共方法相似,不同之处在于它与类共享相同的名称,并且不能返回值。 它可以没有一个,一个或多个参数。

Currently, our constructor method does nothing at all, and it's a good time to consider what this means for the initial state of the Person object. If we left things as they are or we didn't include a constructor method in our Person class (in Java you can define a class without one), then the fields would have no values — and we certainly want our person to have a name and address as well as other characteristics. If you think there's a chance that your object might not be used as you expect and the fields might not be initialized when the object is created, always define them with a default value:

当前,我们的构造函数方法什么也不做,现在是时候考虑这对于Person对象的初始状态意味着什么了。 如果我们保持现状,或者我们的Person类中没有包含构造方法(在Java中,您可以定义一个没有类的类),则字段将没有值-我们当然希望我们的人有一个名字和地址以及其他特征。 如果您认为有可能无法按预期使用对象,并且在创建对象时可能未初始化字段,请始终使用默认值定义它们:

 public class Person {
private String firstName = "";
private String lastName = "";
private String address = "";
private String username = "";
//The constructor method
public Person()
{
}
}

Normally, to ensure that a constructor method is useful, we would design it to expect parameters. The values passed through these parameters can be used to set the values of the private fields:

通常,为确保构造函数方法有用,我们将其设计为带有参数。 通过这些参数传递的值可用于设置私有字段的值:

 public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
// The constructor method
public Person(String personFirstname, String personLastName, String personAddress, String personUsername)
{
firstName = personFirstName;
lastName = personLastName;
address = personAddress;
username = personUsername;
}
// A method to display the state of the object to the screen
public void displayPersonDetails()
{
System.out.println("Name: " + firstName + " " + lastName);
System.out.println("Address: " + address);
System.out.println("Username: " + username);
}
}

Our constructor method now expects the values of four strings to be passed to it. They are then used to set the initial state of the object. We've also added a new method called displayPersonDetails() to enable us to see the state of the object after it has been created.

现在,我们的构造函数方法希望将四个字符串的值传递给它。 然后将它们用于设置对象的初始状态。 我们还添加了一个名为displayPersonDetails()的新方法,使我们能够在对象创建后查看其状态。

调用构造方法 ( Calling the Constructor Method )

Unlike other methods of an object, the constructor method must be called using the "new" keyword:

与对象的其他方法不同,必须使用“ new”关键字来调用构造函数方法:

 public class PersonExample {
public static void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
}

Here's what we did:

这是我们所做的:

  1. To create the new instance of the Person object, we first define a variable of type Person that will hold the object. In this example, we've called it dave.

    为了创建Person对象的新实例,我们首先定义一个Person类型的变量来保存该对象。 在此示例中,我们将其称为dave

  2. On the other side of the equals sign, we call the constructor method of our Person class and pass it four string values. Our constructor method will take those four values and set the initial state of the Person object to be: firstName = "Dave", lastName = "Davidson", address = "12 Main St", username = "DDavidson".

    在等号的另一端,我们调用Person类的构造方法,并向其传递四个字符串值。 我们的构造方法将采用这四个值,并将Person对象的初始状态设置为:firstName =“ Dave”,lastName =“ Davidson”,地址=“ 12 Main St”,用户名=“ DDavidson”。

Notice how we've switched to the Java main class to call the Person object. When you work with objects, programs will span multiple .java files. Make sure you save them in the same folder. To compile and run the program, simply compile and run the Java main class file (i.e., PersonExample.java). The Java compiler is smart enough to realize that you want to compile the Person.java file as well because it can see that you have used it in the PersonExample class.

注意我们如何切换到Java主类来调用Person对象。 使用对象时,程序将跨越多个.java文件 。 确保将它们保存在同一文件夹中。 要编译并运行该程序,只需编译并运行Java 主类文件(即PersonExample.java )。 Java编译器足够聪明,可以意识到您也希望编译Person.java文件,因为它可以看到您在PersonExample类中使用了它。

参数命名 ( Naming of Parameters )

The Java compiler gets confused if the parameters of the constructor method have the same names as the private fields. In this example, you can see that we have distinguished between them by prefixing the parameters with the word "person." It's worth mentioning that there is another way. We can use the "this" keyword instead:

如果构造函数方法的参数与私有字段具有相同的名称,则Java编译器会感到困惑。 在此示例中,您可以看到我们通过在参数前面加上单词“ person”来区分它们。 值得一提的是,还有另一种方法。 我们可以改用“ this”关键字:

 // The constructor method
public Person(String firstName, String lastName, String address, String username)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.username = username;
}

The "this" keyword tells the Java compiler that the variable to be assigned the value is the one defined by the class, not the parameter. It's a question of programming style, but this method helps us define constructor parameters without having to use multiple names.

关键字“ this”告诉Java编译器,要为其赋值的变量是由类定义的变量,而不是参数。 这是编程风格的问题,但是这种方法可以帮助我们定义构造函数参数,而不必使用多个名称。

不止一种构造方法 ( More Than One Constructor Method )

When designing your object classes, you are not limited to using only one constructor method. You might decide there are a couple of ways an object can be initialized. The only constraint on using more than one constructor method is that the parameters must differ.

在设计对象类时,您不仅限于仅使用一种构造方法。 您可能会决定有几种方法可以初始化对象。 使用多个构造函数方法的唯一限制是参数必须不同。

Imagine that at the time we create the Person object, we might not know the username. Let's add a new constructor method that sets the state of the Person object using only the firstName, lastName and address:

想象一下,在创建Person对象时,我们可能不知道用户名。 让我们添加一个新的构造器方法,该方法仅使用firstName,lastName和address设置Person对象的状态:

 public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
// The constructor method
public Person(String firstName, String lastName, String address, String username)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.username = username;
}
// The new constructor method
public Person(String firstName, String lastName, String address)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.username = "";
}
// A method to display the state of the object to the screen
public void displayPersonDetails()
{
System.out.println("Name: " + firstName + " " + lastName);
System.out.println("Address: " + address);
System.out.println("Username: " + username);
}
}

Note that the second constructor method is also called "Person" and it also does not return a value. The only difference between it and the first constructor method is the parameters – this time it expects only three string values: firstName, lastName, and address.

请注意,第二个构造函数方法也称为“ Person”,并且它也不返回值。 它与第一个构造函数方法之间的唯一区别是参数–这次仅需要三个字符串值:firstName,lastName和address。

We can now create Person objects in two different ways:

现在,我们可以通过两种不同的方式创建Person对象:

 public class PersonExample {
public static void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
Person jim = new Person("Jim","Davidson", "15 Kings Road");
dave.displayPersonDetails();
jim.displayPersonDetails();
}
}

Person dave will be created with a firstName, lastName, address, and username. Person jim, however, will not get a username, i.e. the username will be the empty string: username = "".

将使用名字,姓氏,地址和用户名创建人戴夫 。 但是,人员jim将不会获得用户名,即用户名将为空字符串:username =“”。

快速回顾 ( A Quick Recap )

Constructor methods are called only when a new instance of an object is created. They:

仅当创建对象的新实例时才调用构造方法。 他们:

  • Must have the same name as the class

    必须与课程同名
  • Do not return a value

    不返回值
  • Can have none, one, or many parameters

    可以没有一个,一个或多个参数

  • Can number more than one as long as each constructor method has a different set of parameters

    只要每个构造函数方法具有一组不同的参数,就可以编号多个
  • Can have parameter names the same as the private fields as long as the "this" keyword is used

    只要使用“ this”关键字, 参数名称就可以与私有字段相同

  • Are called using the "new" keyword

    使用“新”关键字调用

翻译自: https://www.thoughtco.com/the-constructor-method-2034336

java构造方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值