• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overloading constructors for ArrayLists of different types  RSS feed

 
Bund De
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know if it's my design that is faulty or what... so here's the deal: My simple app has a menu, this menu is a JList that takes its items from a serialized ArrayList that can be of type <Service> or type <Product>.

What I'm trying to do is create two constructors in the PopUpMenu class so it can take both types, but Java is telling me that I cannot overload constructors in this manner:



Is this a problem with my design ? What can I do to improve this ?

Thanks
 
Anayonkar Shivalkar
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bund,

Welcome to CodeRanch!

The first thing comes to my mind is - overriding.

How about your Service and Product classes extend/implement a common abstract class or interface?

Your initialization logic may go in a method (which will reside in interface), and you can override that method in Product and Service.

That way, you can do this task by only one constructor.

I hope this helps.
 
Bund De
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I think I understand what you mean. But what do you mean by my initialization logic? Is it initialization of the Menu, or the Product/Service classes ?

edit: Humm... I think I get it, they should both have a common method so that whichever type gets passed to the constructor is able to call that method.

Thank you!
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bund De wrote:I don't know if it's my design that is faulty or what...

Possibly. And to work that out, you need to ask yourself: "Why do I have Products and Services in the same place"?

That would suggest to me that a Service is a Product (or possibly vice-versa).

If that's not the case, then: yes, I think you should look at your design.

HIH

Winston
 
Bund De
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston,

They are in the same place because I thought one menu would be enough for everything. So what I did now is: I created an "Item" abstract class, and now both Service and Product inherit from Item. This fixed my initial problem.

Do you think I should have multiple menus ?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!