• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enum constructor problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
enum Animals {
DOG("woof"), CAT("meow"), FISH("burble");
String sound;
Animals(String s) { sound = s; } ///should'nt this.sound be used here
}
class TestEnum {
static Animals a;
public static void main(String [] args) {
System.out.println(a.DOG.sound + " " + a.FISH.sound);
}
}
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please QuoteYourSources and UseCodeTags. And next time, write your question out of the code.
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:should'nt this.sound be used here

No. "this." is only required if it otherwise would cause a name clash. If you had renamed "s" to "sound" it would be required. Now the compiler sees that "sound" can only mean its instance field.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic