2

So I was wondering if I could declare an instance field(ex. str1) and a parameter with the same name. Basicly, I ran something akin to

 private String str1;
 private String str2;
 StringTester str= new StringTester(String str1, String str2)
 {
    str1=str1;
    str2=str2;
 }

The tester class printed out null when I asked for str1. Was I supposed to use "this" or is that not applicable at all? (I know this is bad programming convention, but I was just wondering.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Luke Wang
  • 143
  • 2
  • 9
  • 1
    use `this`. i.e., `this.str1 = str1;` – Hovercraft Full Of Eels Oct 19 '14 at 20:55
  • 1
    You're confusing the declaration of a constructor, and the call of a constructor. Re-read your introductory Java book for the syntax of a constructor. And no, this isn't bad practice at all. It's even conventional to name them the same way. – JB Nizet Oct 19 '14 at 21:00
  • OK, this **has** to be a duplicate question, but I can't find the dup. Someone anyone, please help me close this question before we get a million unnecessary answers. – Hovercraft Full Of Eels Oct 19 '14 at 21:00
  • @HovercraftFullOfEels: http://stackoverflow.com/questions/991757/best-practice-for-parameter-naming-in-java-constructors-and-simple-setters ? – JB Nizet Oct 19 '14 at 21:08
  • @JBNizet: looks good, thanks! I love this site, but I sometimes have a devil of a time finding duplicates. – Hovercraft Full Of Eels Oct 19 '14 at 21:21
  • 1
    @HovercraftFullOfEels I use google to find them. It's better at searching than StackOverflow. – JB Nizet Oct 19 '14 at 21:23
  • @HovercraftFullOfEels I searched for duplicates before asking, but I didnt see that. Sorry about that. – Luke Wang Oct 20 '14 at 04:14
  • The question title says this is for a local variable yet the answers and duplicate reference a class variable. Am I missing something here? – Declan McKenna Sep 28 '16 at 17:00
  • @Deco Yeah, the "dup" is kinda different. I didn't really check it out because I just assumed Hovercraft was right. Oh well, it's too late to care now. – Luke Wang Oct 01 '16 at 01:08

2 Answers2

1

Simple

 this.str1 = str1;
 this.str2 = str2;

now call this.str1 , this.str2 anywhere

Danial Hussain
  • 2,488
  • 18
  • 38
1

Your code should be

public class StringTester{
  private String str1;
  private String str2;

  StringTester(String str1, String str2)
  {
     this.str1 = str1;
     this.str2 = str2;
  }
}
Ezequiel
  • 3,477
  • 1
  • 20
  • 28