Thursday, June 25, 2009

All about enums:How to create ,How to use -- part 3

We have seen the basics of enum in part 1 and part 2.Now we will see the advanced aspect that how can you use the enum to declare and use the methods,variables within it.

The question is why we need to declare and use methods and variables in enums?
The answer is to specify the functionality of the enum.All the logical code and selection logic must remain within the enum.This is done for increasing the understandability and performance of program.enum is just like a look up table from which the values are fetched based on certain conditions.

Following is the example how we can use methods and variables within enum:-

enum RAM{ BATTERING_RAM(20),CAPPED_RAM(30),SIEGE_RAM(40) };

RAM(int hitpoints){
this.hitpoints=hitpoints;
}

private int hitpoints;
public int getHitpoints(){
return hitpoints;
}

class TestRam{
RAM ramName;
public static void main(String a[]){
TestRam ram1=new TestRam();
ram1.ramName=RAM.SIEGE_RAM;
Syatem.out.println(ram1.ramName.getHitpoints());
}
}

The above example prints output as the hitpoints of SIEGE_RAM as 40.That is how you can use the methods and variables within an enum.

Suggested Links:-
Home
All about enums:How to create ,How to use -- part 1
All about enums:How to create ,How to use -- part 2
Why java classes are not marked "final"

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP