简体   繁体   中英

Assigning values to object fields in Java?

For example, if I have this:

class Test{
  private int id;

  public Test(int id){
    id=id;
  }
}

In this case, how can I assign the value of the id parameter to the id field?

Use

 this.id = id;

because this refers to the current object.

Learn more here: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Use this :

public Test(int id){
    this.id = id;
}

From here :

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

您可以使用assign:

this.id = id;

data instance hiding is happening here.your local variable is hiding your instance variable. so to access the instance data , always use " this"

so this.name=name

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