• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ENUM

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source: Devaka Cooray's Exam Simulator.



Can anyone explain me the flow of this program. I am getting confused in the order in which the constructor and floor() methods run?
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Menum m1=Menum.A;
Menum(5) constructor runs with value 5; Hence the SOP in Menum runs and prints 5 i.e. the value of s;

m1.floor();
The constant A represents an instance of the enum type and it overrides the method floor(). Here the *m1* reference points to the instance of represented by constant A and thus calls the overridden method floor() which which sets std to 5;

Menum m2=Menum.B;
Same explanation as for Menum.A

m2.floor();
Same explanation as for m1.floor() except that here the overridden floor() method which sets std to 30;

Menum m3=Menum.C;
Same explanation as for Menum.A

m3.floor();
Here since *m3* is referring to constant C which overloads but not overrides floor() method, hence the floor() method of the enum type is called which sets std to 1;

System.out.println(m1+" "+m2+" "+m3);
Here every instance references' toString() method is called which prints 5, 30 and 1 respectively as set above.
[ December 29, 2008: Message edited by: Harvinder Thakur ]
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are confused only for

Menum m3=Menum.C;
m3.floor();


Here C is not overriding floor() method, see C' code.

C(5){
public void floor(int y){
std=55;
}
};

C is overloading here. So for C's case
public void floor(){
std=1;
}

this will run.
 
Edmen Tay
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
When the program run,

Menum m1 = Menum.A;

Compiler will run constructor A(5) and then call,


and the same do for,

Menum m2 = Menum.B;
Menum m3 = Menum.C;

When calling a method floor(); compile will assign an int value to variable std. So,

variable std in m1 is 5
variable std in m2 is 30

Note, There is not method floor() in enum C(5), but floor(int y). Then compiler will look for the method in Menum which assigns 1 to variable std for m3.

This is the method of overriding and polymorphism in Java compiler.

Therefore, you will get output:
5
5
5
[5] [30] [1]

Please correct if i am wrong, Hope this help.

Edmen
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic