Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ENUM Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "ENUM" Watch "ENUM" New topic


Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
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

Joined: Jun 10, 2008
Posts: 231
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;

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

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

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

Joined: Oct 16, 2008
Posts: 952
I think you are confused only for

Menum m3=Menum.C;

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

public void floor(int y){

C is overloading here. So for C's case
public void floor(){

this will run.

Edmen Tay
Ranch Hand

Joined: Oct 21, 2008
Posts: 39
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] [30] [1]

Please correct if i am wrong, Hope this help.

I agree. Here's the link:
subject: ENUM
It's not a secret anymore!