简体   繁体   English

Java 构造函数 - 如何创建它们

[英]Java Constructors - how to create them

I am currently learning Java and I had a question with constructors in Java.我目前正在学习 Java,我对 Java 中的构造函数有疑问。 When learning, I am sometimes seeing constructors written differently, shown in my 2 examples.在学习时,我有时会看到构造函数的写法不同,如我的 2 个示例所示。 Can you please explain what is the difference between these 2 and why you would use one over the other.您能否解释一下这两个之间有什么区别以及为什么要使用其中一个。 One is using "this."一种是使用“这个”。 and the other isn't, this has been confusing me.而另一个不是,这让我很困惑。 is there a proper way to write this.有没有合适的方法来写这个。

Eg1例1

public class Dog {
  String breed;
  boolean hasOwner;
  int age;
    
  public Dog(String dogBreed, boolean dogOwned, int dogYears) {
    
    breed = dogBreed;
    hasOwner = dogOwned;
    age = dogYears;
   

Eg2例2

public class Dog {
  String breed;
  boolean hasOwner;
  int age;
    
  public Dog(String dogBreed, boolean dogOwned, int dogYears) {
    
    this.breed = dogBreed;
    this.hasOwner = dogOwned;
    this.age = dogYears;

Although both of them (examples above) does the same thing but it's always good to refer the instance variables with the this keyword.尽管它们(上面的示例)都做同样的事情,但是用this关键字引用实例变量总是好的。

this is nothing but reference to the self object of the class. this只不过是对 class 的自我 object 的引用。 Hoping that you are already aware of the basics of Java & Object Oriented principles, in Java everything is referred as Objects.希望您已经了解 Java 和 Object 面向原则的基础知识,在 Java 中,所有内容都称为对象。 Even if you try to access variables you have to do it by objects by creating an instance (ie object in simple terms).即使您尝试访问变量,您也必须通过创建实例(即简单来说 object)通过对象来完成。 Coming back to your examples, since you are setting the instance variables you should use by referring this keyword.回到你的例子,因为你正在设置实例变量,你应该通过引用this关键字来使用。 In other words you are explicitly saying that the instance variables of this class should be set with the data being passed as parameters.换句话说,您明确表示class 的实例变量应使用作为参数传递的数据进行设置。

One more thing I would like to point out.我还想指出一件事。 I see that in the Example 2, you have changed the parameter of the constructor just to make sure that Java is not confused with the instance variable and the parameters.我看到在示例 2 中,您更改了构造函数的参数只是为了确保 Java 不会与实例变量和参数混淆。 But while doing that you changed the meaning or descriptive intent of the parameters.但是在这样做的同时,您改变了参数的含义或描述性意图。 This could have been avoided something like below -这本可以避免,如下所示 -

public class Dog {
  String breed;
  boolean hasOwner;
  int age;
    
  public Dog(String breed, boolean hasOwner, int age) {
    
    this.breed = breed;    
    this.hasOwner = hasOwner;
    this.age = age;

    // Any this.variables are referred as the instance  variables and the ones
    // without the this are referred as the parameters. 
  }
}

I hope that you have now understood purpose of the this keyword.我希望您现在已经理解了this关键字的用途。 Remember this is not restricted only to variables but can also be used with methods.请记住this不仅限于变量,还可以与方法一起使用。 As long as you remember the that this is nothing but reference to self, you will never get confused.只要您记住this只是对自我的引用,您就永远不会感到困惑。

This is pretty basic, but for proper decision you may consider knowing the poper meaning of this .这是非常基本的,但为了做出正确的决定,您可以考虑了解this的流行含义。

In your given examples, both are fine, with and without the use of this but the 2. example is overkill due to the following reason: We use this to refer to the Object we are creating.在您给定的示例中,无论是否使用this都很好,但 2. 示例由于以下原因而过度杀伤:我们使用this来指代我们正在创建的 Object。 In your example 2 this and Dog we can say they are the same thing inside that context.在您的示例 2 中, this和 Dog 我们可以说它们在该上下文中是相同的。 So say: Dog chien = new Dog(...);所以说: Dog chien = new Dog(...); inside the class Dog the use of this would be the same as chien or any other Dog object you have created.在 class Dog 内部,使用thischien或您创建的任何其他Dog object 相同。

So why using this ?那么为什么要使用this呢? Ones of the basic reasons are Parameter given to the constructor or to the methods, in case you name them the same as the atributes.一个基本原因是为构造函数或方法提供了参数,以防您将它们命名为与属性相同的名称。

For example you can do:例如,您可以这样做:

public class Dog { 
            String breed; 
            boolean hasOwner;
            int age; 
     
  public Dog(String breed, boolean hasOwner, int age) { 
             this.breed = breed;
             this.hasOwner = hasOwner;
             this.age = age;

This is valid as well as your exaple 1. With this you indicate that to the Dog's attribute you want to asign a value, wich is given as a parameter.这和您的示例 1 一样有效。有了this ,您表明您想要为 Dog 的属性分配一个值,该值作为参数给出。 Otherwise you avoid writing such ambiguity like breed = breed .否则,您可以避免编写像breed = breed这样的歧义。

All in all, if the name of your parameters are different from the name of your attributes, then you don't need to use this , so no need both examples 1 and 2 are fine, but no need for it at 2., example 1 is just fine.总而言之,如果您的参数名称与属性名称不同,则不需要使用this ,因此不需要示例 1 和 2 都可以,但在 2 中不需要它,例如1刚刚好。 However for further concepts in java, it is a good practise to get used to this as self reference the the object.然而,对于 java 中的更多概念,习惯于将this作为 object 的自我参考是一个很好的做法。 That may help you get better understanding of future useful thigs in java.这可能有助于您更好地了解 java 中未来有用的东西。

In Java, a constructor is a block of codes similar to the method.在 Java 中,构造函数是与方法类似的代码块。 It is called when an instance of the class is created.在创建 class 的实例时调用它。 At the time of calling constructor, memory for the object is allocated in the memory.在调用构造函数时,memory中分配了object的memory。

It is a special type of method which is used to initialize the object.这是一种特殊的方法,用于初始化 object。 Every time an object is created using the new() keyword, at least one constructor is called.每次使用 new() 关键字创建 object 时,都会调用至少一个构造函数。

Keyword this is a reference variable in Java that refers to the current object.关键字this是 Java 中的引用变量,它引用当前的 object。 When we use the same parameters in the constructor that similar to variables that defined we use this keyword in the constructor.当我们在构造函数中使用与定义的变量相似的相同参数时,我们在构造函数中使用 this 关键字。

public class Dog {
String breed;
boolean hasOwner;
int age;

public Dog(String dogBreed, boolean dogOwned, int dogYears) {

  this.breed = dogBreed;
  this.hasOwner = dogOwned;
  this.age = dogYears;

When you use this assign the value of parameter.当您使用时,分配参数的值。

public class Dog{
    String breed;
    boolean hasOwner;
    int age;
    public Dog(String dogBreed, boolean dogOwned, int dogYears){
        this.breed = dogBreed;
        this.hasOwner = dogOwned;
        this.age = dogYears;
    }
}

So now, if you don't use "this" keyword of java, the compiler can't understand when you trying use your local variable and you output show zero or depend.所以现在,如果你不使用 java 的“this”关键字,当你尝试使用你的局部变量并且你 output 显示为零或依赖时,编译器将无法理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM