Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a variable is used before declaration in enum and its running ok how

 
kapilg gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
enum Coffesize{

BIG(8),HUGE(10);
Cofeesize (int ounces)
{
this.ounces=ounces;
}
private int ounces;
public int getOunces()
{return ounces;
}
}
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Member variables don't have to be declared before they are used. As long as the member variable is declared in the class (or enum) somewhere, it will work.
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Member variables don't have to be declared before they are used.


Agree. In fact, I think, there is no order of declarations or methods. There is a conventional order we write things down in, but the order of declarations ro methods does not affect the compilation of a class.

The only place where order matters (I think) is inside a method.
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only place where order matters (I think) is inside a method.


Sorry, I forgot: A package statement has to precede your import statements which precede your class declaration.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:

The only place where order matters (I think) is inside a method.


Static initializers and expressions used to initialize static fields are executed in their listed order:


Ditto for instance initializers and instance fields:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic