Results 1 to 5 of 5
- 08-04-2011, 03:34 AM #1
Member
- Join Date
- Aug 2011
- Posts
- 5
- Rep Power
- 0
Using Generic Methods like Templates?
I have taking about a year in c++ and am trying to learn java right now. I'm really confused about generics because it looks like templates in c++ to me. Here is a snippet of my code that wont work.
public static <T> void monsterMain(T monster)
{
monster.getStats();
}
There are 4 different data types that can be passed to this method. The function in the derived class getStats() works fine, I have tested it other places. The error I get is:
'cannot find symbol'
'symbol: method getStats()'
Each derived class has a redefined function getStats() so the calling data type shouldn't be an issue. Any help would be mucho appreciated.
- 08-04-2011, 03:41 AM #2
What happens if I pass a String to that method? String does not have a getStats method. Perhaps you should be using Inheritance instead of Generics. You say you have 4 different data types. Do they all extend from the same Parent class? If so make the parameter type to your method be the Parent class.
- 08-04-2011, 04:14 AM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Also if they all implement getStats, you can have them all implement and interface and pass in a type of the interface(this is nearly identical to what junky said, except he referred to inheritance)
- 08-04-2011, 08:04 AM #4
Member
- Join Date
- Aug 2011
- Posts
- 5
- Rep Power
- 0
The four different data types are classes inherited from one parent class. If I make The data type the parent class wouldn't I be guilty of data slicing. Also the function getStats isn't part of the parent class. Would it data slice if I make the argument the parent classes data type?
- 08-04-2011, 08:16 AM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,603
- Blog Entries
- 7
- Rep Power
- 17
When people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
Change the signatures of the conflicting methods in generic class ?
By FOUAD-SPIDER in forum New To JavaReplies: 7Last Post: 02-27-2011, 01:17 AM -
HELP! - Eclipse Templates
By protocos in forum EclipseReplies: 1Last Post: 03-06-2009, 02:31 AM -
Generic methods
By andre1011 in forum Advanced JavaReplies: 7Last Post: 02-25-2009, 02:17 PM -
Writing generic methods
By eva in forum New To JavaReplies: 2Last Post: 12-31-2007, 03:28 AM -
Templates JSP
By Eric in forum JavaServer Pages (JSP) and JSTLReplies: 2Last Post: 07-04-2007, 07:42 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks