简体   繁体   中英

Java Constructors - how to create them

I am currently learning Java and I had a question with constructors in Java. When learning, I am sometimes seeing constructors written differently, shown in my 2 examples. 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

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

Eg2

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 is nothing but reference to the self object of the class. Hoping that you are already aware of the basics of Java & Object Oriented principles, in Java everything is referred as Objects. Even if you try to access variables you have to do it by objects by creating an instance (ie object in simple terms). Coming back to your examples, since you are setting the instance variables you should use by referring this keyword. In other words you are explicitly saying that the instance variables of this class should be set with the data being passed as parameters.

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. 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. Remember this is not restricted only to variables but can also be used with methods. As long as you remember the that this is nothing but reference to self, you will never get confused.

This is pretty basic, but for proper decision you may consider knowing the poper meaning of 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. In your example 2 this and Dog we can say they are the same thing inside that context. So say: 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.

So why using 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. Otherwise you avoid writing such ambiguity like 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. However for further concepts in java, it is a good practise to get used to this as self reference the the object. That may help you get better understanding of future useful thigs in java.

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Keyword this is a reference variable in Java that refers to the current object. When we use the same parameters in the constructor that similar to variables that defined we use this keyword in the constructor.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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