[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

abstract method in enum

Posted on 2014-08-01
17
Medium Priority
?
244 Views
Last Modified: 2014-08-10
Hi,

I was reading below link


http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html#ixzz39ALX5kTO


and the example
public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
          ..............

}

Open in new window


I wonder why we need abstract kind of methods inside enums. what are the practical use of it. what design pattern is being used.Please advise
0
Comment
Question by:gudii9
  • 10
  • 6
17 Comments
 
LVL 28

Accepted Solution

by:
dpearson earned 1400 total points
ID: 40235213
Attaching extra properties to an enum is a generally useful pattern.

For example here the class supports things like:
   
   Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is " + coins.color()) ;
   }

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;

This is cleaner than if we stored the color separately from the enum:

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is ") ;
        switch (coins) {
             case NICKLE: System.out.println("Bronze") ; break ;
             case QUARTER: System.out.println("Silver") ; break ;
             ...
        }
   }

So the pattern is regular data encapsulation - just like any other object.
This is just an example showing how to do it within an enum, which doesn't support "extends" like a normal class does.

Hope that helps,

Doug
0
 
LVL 21

Assisted Solution

by:Amitkumar P
Amitkumar P earned 600 total points
ID: 40236106
Agree with Doug.

Just adding one small thing. I would say adding an abstract method is an implementation of Strategy design pattern where every Enum has different logic based on what type it is.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40237857
  Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is " + coins.color()) ;
   }

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;

This is cleaner than if we stored the color separately from the enum:

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is ") ;
        switch (coins) {
             case NICKLE: System.out.println("Bronze") ; break ;
             case QUARTER: System.out.println("Silver") ; break ;
             ...
        }
   }


I am not able to understand above code. Is above code is in a single class or enum?

can you please post me full code.
Is strategy design pattern is java design patern or j2ee design pattern?
please advise
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 28

Expert Comment

by:dpearson
ID: 40238370
This half of the code uses the enum that you defined:

Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is " + coins.color()) ;
   }

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;

Open in new window


It can go into any class you like.
E.g. You can put that code inside the "main" method of a program to make it run.


This code also uses the enum that you defined but it doesn't make use of the "color" method in the enum.
So it's showing the benefit of having that method inside the enum because this "printMoneyColor" method is a lot longer than the method above.

   public void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is ") ;
        switch (coins) {
             case NICKLE: System.out.println("Bronze") ; break ;
             case QUARTER: System.out.println("Silver") ; break ;
             ...
        }
   }

Open in new window


I hope that helps explain things.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40242354
public abstract String color();

Open in new window


Above is abstract method right in enum right. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40242357
can you please share complete working example which i can run and see output and understand it completely?
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40242394
Something like this should work:

public class MyDemo {

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
}

   public static void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is " + coins.color()) ;
   }

public static void main(String args[]) {
   Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;
}

}

Open in new window


Then replace the printMoneyColor() with the other method if you wish to see the alternative.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40242851
package eePackage;

public class MyDemo {

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }

				@Override
				public void run() {
					// TODO Auto-generated method stub
					
				}
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }

				@Override
				public void run() {
					// TODO Auto-generated method stub
					
				}
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }

				@Override
				public void run() {
					// TODO Auto-generated method stub
					
				}
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }

				@Override
				public void run() {
					// TODO Auto-generated method stub
					
				}
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
}

   public static void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is " + coins.color()) ;
   }

public static void main(String args[]) {
   Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;
}

}

Open in new window



I have to implement Run() method in all methods like PENNY, DIME etc

I wonder why i have to implement run method in all those methodss?

I got output like

The color of money QUARTER is silver
The color of money DIME is silver

Then replace the printMoneyColor() with the other method if you wish to see the alternative.

can you please post the complete code for this alternate solution also. I have not got it.
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40242926
OK here's the same code with a different print method:

public class MyDemo {

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();

          public void run() {
                 System.out.println("You can implement Runnable in one place if you want") ;
          }
        
          private Currency(int value) {
                  this.value = value;
          }
}

   public static void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is ") ;
        switch (coins) {
             case DIME: System.out.println("Silver") ; break ;
             case NICKLE: System.out.println("Bronze") ; break ;
             case QUARTER: System.out.println("Silver") ; break ;
        }
   }

public static void main(String args[]) {
   Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;
}

}

Open in new window


The whole point is to compare the code inside the two printMoneyColor methods.  I hope you're able to see that one is shorter than the other.

Also I showed you how to implement Runnable with just one method, not adding it to each member of the enum.

Hope that helps,

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40244211
public class MyDemo {

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();

          public void run() {
                 System.out.println("You can implement Runnable in one place if you want") ;
          }
        
          private Currency(int value) {
                  this.value = value;
          }
}

   public static void printMoneyColor(Currency coins) {
        System.out.println("The color of money " + coins + " is ") ;
        switch (coins) {
             case DIME: System.out.println("Silver") ; break ;
             case NICKLE: System.out.println("Bronze") ; break ;
             case QUARTER: System.out.println("SilverQuarter") ; break ;
        }
   }

public static void main(String args[]) {
   Currency myCoins = Currency.QUARTER ;
   Currency myOtherCoins = Currency.DIME ;

   printMoneyColor(myCoins) ;
   printMoneyColor(myOtherCoins) ;
}

}

Open in new window


I ran code as above.

I got response as below

The color of money QUARTER is
SilverQuarter
The color of money DIME is
Silver


It is feeling better to see run() method implemented only once at the bottom instead of implementing exch DIME, QUARTER etc blocks.

I wonder why are we implementing runnable? Is there is any relationof runnable with reference to enum or abstract methods. Please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40244215
PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }

Open in new window


what do you call above block which says PENNY(1).

It is containg color() method but looks like method only, is it is like outer method? or enum method or block. please advise
0
 
LVL 7

Author Comment

by:gudii9
ID: 40244221
The whole point is to compare the code inside the two printMoneyColor methods.  I hope you're able to see that one is shorter than the other.

I see big method is giving more specific message to type of coin being selected with switch case condition right?
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40245215
I see big method is giving more specific message to type of coin being selected with switch case condition right?

The intention is that both sets of code generate basically the same output.  The bigger method takes more code in the printMoneyColor() method.  The abstract method approach inside the enum puts more code into the enum.

I wonder why are we implementing runnable? Is there is any relationof runnable with reference to enum or abstract methods. Please advise
They chose to implement Runnable in the example just because it's a convenient interface that already exists.  It's a ridiculous choice for this - you would never "Run" a color.  You "Run" tasks.  So don't focus on the choice of Runnable.  Just that this is an example of any interface and how you could implement it inside an enum.

Hope it's all clear now.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40245308
The abstract method approach inside the enum puts more code into the enum.


when you say abstract method you mean below method right


 public abstract String color();


which is basically inside the enum.

I do not see enum extends abstract class etc.

So how the abstract method implementation also given in same enum. I am bit confused there. please advise
0
 
LVL 28

Expert Comment

by:dpearson
ID: 40245318
I do not see enum extends abstract class etc.

Right.  In an enum it's a bit different.  You can define an abstract method like this:

public enum Currency {
   ...
   public abstract String color();
} ;

which is then implemented by the instances of the enum:

PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }

It behaves almost like "PENNY" is a subclass of the enum Currency.
It's not, but it's like that.

Doug
0
 
LVL 7

Author Comment

by:gudii9
ID: 40245322
which is then implemented by the instances of the enum:

PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }

these are instances of enum. Interesting to know and see instances of enum which looks weird compared to object instances but now it all makes more sense
0
 
LVL 7

Author Comment

by:gudii9
ID: 40245326
It behaves almost like "PENNY" is a subclass of the enum Currency.

does the psudo subclass PENNY does anything other than implementing the abstract method. Does it obey any other object oriented properties of inheritance etc? please advise
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month18 days, 1 hour left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question