• Post Reply Bookmark Topic Watch Topic
  • New Topic

generic method  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mala Gupta & everyone

hopefully everyone is fine.Here is my problem statement:

On code below, I am failing to understand clearly why iob.sameAvg(dob) in main method can not be applied to this method sameAvg(Stats<T> ob) yet T refers to any class which implements Number interface?


Pliz !! help, I am stuck.
 
author
Sheriff
Posts: 23306
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

tau murinda wrote:
On code below, I am failing to understand clearly why iob.sameAvg(dob) in main method can not be applied to this method sameAvg(Stats<T> ob) yet T refers to any class which implements Number interface?



It's a generic type mismatch. The iob variable is a Stats<Integer> object, so the method is working with an Integer generic type. You are passing a parameter with a different generic type.

Perhaps you wanted to make the sameAvg() method a generic method instead? In that case, there will be two generic types. One for the object (this). One for the method (local object). And your method is responsible for managing the differences.

Henry
 
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tau as Henry mentioned, your method sameAvg will take only an Object of Stats which has the same type T.

As Henry said, this is because the method has the same type as the instance
class Stats<T extends Number> {
...
boolean sameAvg(Stats<T> ob) {
...


If you want the method to be able to accept any Status object, you'll have to define the type in the method, something like:
<E extends Number> boolean sameAvg(Stats<E> ob)

Now your method will be able to accept any Stats object...
 
tau murinda
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Henry

Thank you Henry, it is now done and done, now diving into generic methods to get much of it.
 
tau murinda
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ankit,thank you guys
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!