import java.io.*;
public class EnumEx3
{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Fishs fishs=Fishs.AMNON;
		System.out.println(fishs.getX());
	}


	
}

enum Fishs
{
	BURI(20),
	AMNON(50);
	private int x;
	private Fishs(int x) {
		this.x=x;
	}
	public int getX() {
		return x;
	}
}

i have that code and i have no clue , why when i call the getX method from the main, the value of BURI is printed?
how do they connect , whats the process that happens inside java?

Recommended Answers

All 12 Replies

An enum is just like a class that has a number of instances defined at compile time. You can think of it as if Fishes is a class, with exactly two instances.
BURI and AMNON are like two public static final variables that hold references to the two instances.
Lines 22-24 are the constructor for Fishes. It's called with the parameters 20 and 50 for the two instances, and it stores the values 20 and 50 in the instance variable x.
The getX method does exact.ly what you would expect.
The print on line 10 should therefore print 50.

OOh . okay, so the point is that the two instance variables are"

public static final AMNON
public static final BURI

okay i got it!
it got me confused , cause i know that you could treat the two instances as if they were classes.

you can open them ..
say : Buri{
public int return(){
return x;
}
}


why can you treat Buri and Amnon as instance variables and as classes?

can you explain this to me, james? cause i dont think i grasp that idea conceptually

BURI and AMNON are not classes, and you cannot treat them as classes.
They are not instance variables, and you cannot treat them as instance variables.
They are like static final references to two instances of the enum
Yoi cannot "open" them.
The code you posted is not valid.

All it is saying is that there are exactly two Fishs, one called BURI one called AMNON. They both have an attribute called "x", which has the value 20 for BURI and 50 for AMNON.

ps. Please be careful with your capitalisation. Java is case-sensitive. There is no such thing as an Enum (well, strictly there is, but you don't use it), nor are there Fishs called Amnon or Buri.

import java.io.*;
public class EnumEx7
{

    /**
     * @param args
     */
    public static void main(String[] args) {
        Misada misada=new Misada();
        System.out.println(misada.getPrice(Fishs.BURI));
        System.out.println(Fishs.BURI.SayHello());
    }


    static String readLine() {
          try {
           return new BufferedReader(new InputStreamReader(System.in))
             .readLine();
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
          return null;
     }
}

enum Fishs
{
    BURI(20){
        @Override
        public int getPrice() {
            return super.getPrice()*super.getPrice();
        }
        public String SayHello(){
            return "BURI: Hello";
        }
    },
    AMNON(50) {
        @Override
        public String SayHello() {
            // TODO Auto-generated method stub
            return null;
        }
    };



    private int x;
    private Fishs(int x) {
        this.x=x;
    }
    public int getPrice() {
        return x;
    }
    abstract String SayHello();
}
class Misada{
    public int getPrice(Fishs fish){
        return fish.getPrice();
    }
}

That code actually does work? how can you conceptually explain that.
how can i put methods inside those static final references to enum

As I said, its like a final static enum; I was trying to keep things simple. It's actually more complicated than that.
The example you show is defining an overridden version of the SayHello() method for each instance of the enum. There's also one override of the getPrice() method, although it doesn't make any sense. (These methods are known as constant-specific methods.)
This is a fairly advanced and rare facility, which you won't see often. This is the point where the simple analogy of class/static vars breaks down - there is no corresponding construct for an ordinary class (unless someone else can correct me on that?), it's more like defining inner sub-classes of the enum, but its not exactly that either, It just is what it is.

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

class BlockBuster{
    public static void main(String[] args){
        Games game= new Games();
        String gamesName;
        String stop;
        Charactaristics gamer;
        HashMap<String,Charactaristics> choice= new HashMap<String,Charactaristics>();
        int gameBuy;
        String gamelist[]=new String[8];
        gamelist[1]=game.getName(Charactaristics.FALLOUTVEGAS);
        gamelist[2]=game.getName(Charactaristics.GODOFWAR); 
        gamelist[3]=game.getName(Charactaristics.AGEOFEMPIRESONLINE);
        gamelist[4]=game.getName(Charactaristics.DIRT3);                                         
        gamelist[5]=game.getName(Charactaristics.DEUSEX);
        gamelist[6]=game.getName(Charactaristics.CRYSIS2);
        gamelist[7]=game.getName(Charactaristics.BIOSHOCKINFINITY);
      
        
        Charactaristics gamelist2[]=new Charactaristics[8];
        gamelist2[1]=Charactaristics.FALLOUTVEGAS;
        gamelist2[2]=Charactaristics.GODOFWAR; 
        gamelist2[3]=Charactaristics.AGEOFEMPIRESONLINE;
        gamelist2[4]=Charactaristics.DIRT3;                                         
        gamelist2[5]=Charactaristics.DEUSEX;
        gamelist2[6]= Charactaristics.CRYSIS2;
        gamelist2[7]=Charactaristics.BIOSHOCKINFINITY;
                                   
              while(true){
            for(int i=0;i<gamelist.length;i++){
                System.out.println(gamelist[i]);
            }
            System.out.println("What game are you going to buy?(Enter a number)");
            gameBuy=Integer.parseInt(readLine());
            gamer=gamelist2[gameBuy];
            System.out.println("Whats the games name?");
            gamesName=readLine();
            System.out.println("if you want to stop type -Stop");
            stop=readLine();
            choice.put(gamesName, gamer);
            if(stop.equals("Stop")){
                break;
            }
            
              }
              
              
              while(true){
                  System.out.println("On which game do you want to get information about? ");
                  gamesName=readLine();
                     
                  if(choice.containsKey(gamesName)){
                      System.out.println(game.getPrice(choice.get(gamesName)));
                      System.out.println(game.getDescription(choice.get(gamesName)));
                      System.out.println(game.isItWorty(choice.get(gamesName)));
                      System.out.println(game.getName(choice.get(gamesName)));
                      
                  }
                  else{
                      System.out.println("No");
                  }
                      
                      
                      
                  
                  System.out.println("if you want to stop type -Stop");
                stop=readLine();
                if(stop.equals("Stop"))
                    break;
              }
        
    }
    static String readLine() {
          try {
           return new BufferedReader(new InputStreamReader(System.in))
             .readLine();
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
          return null;
     }
}




enum Charactaristics{
    FALLOUTVEGAS{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "Awesome Game , but worth downloading cause there is no multiplayer";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 200;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "Worthy Downloading";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "1. Fallout New Vegas";
        }
        
    },
    GODOFWAR{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "Good Game, the only good game on the psp";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 250;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "Worthy downloading only, cause the psp is dead";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "2. God of War";
        }
        
    },
    AGEOFEMPIRESONLINE{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "A very unique game, good game, flawless";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "worth getting cause it is free";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "3. Age of Empires Online";
        }
        
    },
    DIRT3{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "Best looking racing game..A very good game";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 250;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "Worths buying cause such games last for long, the multiplayer functionality is fun";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "4. Dirt 3";
        }
        
    },
    DEUSEX{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "The storyline looks awesome";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 300;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "Worth seeing only what the game is about";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "5. Deus Ex";
        }
        
    },
    CRYSIS2{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "It is a boring FPS";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 299;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "not worth getting cause the graphics are too good for my pc";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "6. Crysis 2";
        }
        
    },
    BIOSHOCKINFINITY{

        @Override
        public String getDescription() {
            // TODO Auto-generated method stub
            return "A decent FPS, but not great";
        }

        @Override
        public int getPrice() {
            // TODO Auto-generated method stub
            return 250;
        }

        @Override
        public String isItWorty() {
            // TODO Auto-generated method stub
            return "not worth buying";
        }

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "7. Bioshock Infinity";
        }
        
    };
    
    
    
    abstract int getPrice();
    abstract String getDescription();
    abstract String isItWorty();
    abstract String getName();
    
}

class Games{
    public int getPrice(Charactaristics game){
        return game.getPrice();
    }
    public  String getDescription(Charactaristics game){
        return game.getDescription();
    }
    public String isItWorty(Charactaristics game){
        return game.isItWorty();
    }
    public String getName(Charactaristics game){
        return game.getName();
    }
    
}

i have written this code this morning by myself. i was explained in class those static enum variables inherit from enum class.

enums are a thing in their own right - and have characteristics that ordinary classes do not, particularly constant-specific methods. However, these are so rare in practice that you can not worry about them. In Java words like "variables", "inherit", "class" have absolutely specific meanings, so a statement like "static enum variables inherit from enum class" conveys a general feel of what happens, but is a false statement. variables cannot inherit.

As for your code:
What's the point of the Games class? All it does is provide a set of covers for methods that need no cover. It seems to be pure overhead with no value.
You have used constant-specific methods, presumably because we were talking about them, but there's no need for them in your example. They are a log and tedious way to achieve that result. The code will be shorter and clearer if you make description, price, isWorthy and name simple variables and set them in a constructor. Like this:

enum Charactaristics{
  FALLOUTVEGAS("Awesome Game , but worth downloading cause there is no multiplayer",
               200, true, "1. Fallout New Vegas"),

  GODOFWAR("Good Game, the only good game on the psp"  ... etc

  private String decription;
  private int price;
  private boolean isWorthy;
  private String name;

  Charactaristics(String decription, int price, boolean isWorthy, String name) {
    this .decsription = description;
    etc
  }

   public String getDescription() {return description;}
   etc
}

Finally, you use two arrays fro game names and enum constants, and build a map to relate them.
This may not be necessary because all enums inherit a static valueOf method that returns the the enum constant given its name. You can also use the enum's values() method to get an array of all the constants, so you don't need to create one yourself.

i know james, but i was practicing the enum and its variables. of course, there is a shorter way to produce the final output without going through that hell..

so how conceptually would you define the "games " inside the enum class.
if they are not classes, how are they generated, where are they kept inside the memory?

"conceptually" I would stick with thinking of them as static final variables containing references to the different enum instances. Its only constant-specific methods that don't fit the simple summary. They are generated by the equivalent of something like this:
enum Month{ JAN(31), etc
is like:
enum Month {
public static Month JAN = new Month(31);
etc

I'm away now till tomorrow. Good luck.

commented: okay, thanks james +0

if they are not classes, how are they generated, where are they kept inside the memory?

Enums get special treatment by the compiler and impose additional restrictions not imposed by regular classes, specifically not having the ability to extend any class since they are automatically made to extend the Enum class. But after compilation, there is no such thing as an "enum", its classes all the way.

Regarding methods; every time you declare an enum constant having class body, a corresponding anonymous inner class is created which extends the enclosing enum class. So for e.g. with the following piece code:

enum Suit {
  HEART {
    public void doIt() {}
  },
  SPADE {
    public void doIt() {}
  };
  public abstract doIt();
}

the classes created would be Suit.class, Suit$1.class and Suit$2.class where the latter two classes extend the Suit class.

anonymous inner classes.. i see now. i got your idea.

it is like i do something like that.. (suppose they were classes not enum).

Suit s=new Suit(){
public void print(){
System.out.println("i am happy");
}
}

am i being correct?

Yes, something along those lines. For e.g. a enum like:

enum Suit {

    HEART(1) {
        @Override
        public void doIt() {
            System.out.println("I'm a HEART");
        }
    },
    SPADE(2) {
        @Override
        public void doIt() {
            System.out.println("I'm a SPADE");
        }
    },
    CLUB(3) {
        @Override
        public void doIt() {
            System.out.println("I'm a CLUB");
        }
    },
    DIAMOND(4);


    private Suit(int i) {
        this.i = i;
    }

    private final int i;
    
    public void doIt() {
        System.out.println("HI");
    }

}

would be translated to something along the lines of:

class SuitClass {

    public static final SuitClass HEART;
    
    public static final SuitClass SPADE;

    public static final SuitClass CLUB;

    public static final SuitClass DIAMOND;

    private String enumName;

    private int pos;

    private int i;

    static {
        HEART = new SuitClass("HEART", 0, 1) {
            public void doIt() {
                System.out.println("I'm a HEART");
            }
        };
        SPADE = new SuitClass("SPADE", 1, 2) {
            public void doIt() {
                System.out.println("I'm a SPADE");
            }
        };
        CLUB = new SuitClass("CLUB", 2, 3) {
            public void doIt() {
                System.out.println("I'm a SPADE");
            }
        };
        DIAMOND = new SuitClass("DIAMOND", 3, 4);

    }

    private SuitClass(String enumName, int pos, int j) {
        this.enumName = enumName; // teh enum name
        this.pos = pos; // the enum position
        this.i = i; // the instance variable of enum
    }

    public void doIt() {
        System.out.println("HI");
    }

}
commented: well understood. thank you +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.