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:
Post a Comment
Post a Comment