• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

enum Query

 
nitin pokhriyal
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

I have a query regarding enum type it may be look silly. Suppose i have defined a enum Grade in TestObj class

1. public enum Grade{
2.A(1),B(2),C(3);
3. public int a;
4.Grade(int a){
5.this.a=a;
6.}

if i try to access it in my main method. it is working fine.

1. public static void main(String[] args){
2. Grade grade=Grade.A;
3. out.println(grade.a);
4. }

Why i don't have to type
TestObj.Grade grTest=TestObj.Grade.A; why it is simply
Grade grade=Grade.A;

Thank in advance
Nitin
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nitin,


What is TestObj? You know in a source file, there can be only one
public class, interface or enum type. So to make your TestObj class
public, you need to keep it in separate file and your enum in another one.

If the enum is inside the class TestObj, you can access in the class,
without prefixing enclosing class name.


Thanks,
 
nitin pokhriyal
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just want my assumptions to be correct.
Thanks chandra

regards,
nitin
 
Tashi Rautela
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the result of compiling and running the following code?
enum Level {
NOVICE, MEDIUM, EXPERT; // line 1
public void checkLevel(Level l1, Level l2) { // line 2
System.out.println(l1.toString().length() + l2.toString().length()); // line 3
}
}
class EnumFour {
public static void main(String[] args) {
Level level = Level.NOVICE; // line 5
level.checkLevel(level, Level.EXPERT); // line 6
}
}

Options :
a) error at line 2. Non static method cannot be declared with in a enum.
b) error at line 3.
c) error at line 5. assignment is not valid syntax.
d) Compiles file and Prints output 12.
e) COmpiles fine but runtime Exception will be thrown.

the ans is 'd' output 12,how has it come...
 
Ashu Pandey
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NOVICE length =6
EXPERT length =6
total =12
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic