0

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?

1
  • this.id=id this means the current instance Commented Sep 22, 2013 at 3:39

4 Answers 4

2

Use

 this.id = id;

because this refers to the current object.

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

Sign up to request clarification or add additional context in comments.

1 Comment

...because the method parameter id shadows the instance field id.
1

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.

Comments

0

You can use assign:

this.id = id;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.