• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Enums and the toString method

 
Varnam Aayiram
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks...

I was trying out a certain exercise from the book 'murach's Java SE6'. It's question 5 of esercise 9-4.The question from the book is as follow:

"Add a toString method to the CustomerType enumeration. This method should return a string that contains "Retail Customer", 'Trade Customer" or "College

customer" depending on the customer type. Compile this class , then run the CustomerTypeApp class again to view the results of te toString method."

My code are as follow:

CustomerType



CustomerTypeApp



The question asks to return an appropriate string based on the customer type. I haven't gone to that extend of returning based on the customer type as I seem to be having problem returing via the toString method. I understand that I cannot instantiate the enum in the 'CustomerTypeApp' class, how than do I call the toString method from withing the 'CustomerTypeApp' class? I hope someone can advise. Thanks.
 
Henry Wong
author
Marshal
Pie
Posts: 20882
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Varnam Aayiram wrote:
I understand that I cannot instantiate the enum in the 'CustomerTypeApp' class, how than do I call the toString method from withing the 'CustomerTypeApp' class? I hope someone can advise. Thanks.


CustomerType.RETAIL.toString() ?


or if you have it assigned to a variable...

private CustomerType ct = CustomerType.RETAIL;

then ct.toString() ?

 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need a method to return "Retail Customer", 'Trade Customer" or "College customer" , depending on the Customer Type you will need to associate "Retail Customer", 'Trade Customer" or "College customer" with each of the Customer type

i.e : RETAIL => "Retail Customer" , TRADE => "Trade Customer" and COLLEGE => "College Customer".

You can do that by using Constructors for Enum and return the associated values with toString() method.

The toString() method will look as follows:

String toString(CustomerType c)
{
return(c.type);
}
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's not a toString() method, that's a toString(CustomerType) method. It will not be called when you try to print out one of the enum constants itself. But yes, the idea is good:
 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Rob: you are right , i did not override the toString() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic