user1056027
user1056027

Reputation: 145

java generic method fundamentals

i am running some tests to better understand java generic methods, and came across the following problem. i have the following simple class:

1    public class SomeClass<O extends Object> {
2    
3        O someVar;
4    
5        public SomeClass() {
6           someFunc(new Number(1));
7        }
8    
9        public void someFunc(O arg) {
10           // code
11        }
12    }

as it stands, the compiler does not like line 6. eclipse suggests to either cast Number instance to O, or change argument type to Number on line 9. i would really like to avoid both if possible. i know that modifying the class like so takes care of this problem:

1    public class SomeClass {
2    
3        O someVar;
4    
5        public SomeClass() {
6           someFunc(new Number(1));
7        }
8    
9        public <O extends Object> void someFunc(O arg) {
10           // code
11        }
12    }

but that brings a new problem with line 3.

so what can be done with my original code?

thank you for your time!!!

Upvotes: 0

Views: 159

Answers (3)

Petar Ivanov
Petar Ivanov

Reputation: 93080

The problem is that with <O extends Object> you declare that O can be any type that extends Object (so really any type - you could have changed it to <O>).

Then your function someFunc is declared to accept an argument of type O, but then you pass a Number. There is no guarantee that Number is O.

None of the solutions that eclipse suggests is good:

If you cast the Number to O you might get an error, since Number is not O (remember O can be anything) If you change the argument to Number, then you can pass the private variable and I assume that's what you want.

Upvotes: 0

Apurv
Apurv

Reputation: 3753

You can add an overloaded method that excepts Number as an arguent.

public void someFunc(Number n) {
    // code
}

Upvotes: 0

Rickard
Rickard

Reputation: 7277

The problem in your first example is that you are creating a class SomeClass where O can be anything that extends Object (or Object).

For example new SomeClass<HashMap>();

Now the compiler will have a constructor which tries to pass Number, to a method that wants an O in this case a HashMap.

Change your constructor to take an argument O something which you pass to someFunc.

public SomeClass(O something) {
  someFunc(something);
}

If you know you want to create and pass around a Number your generic should instead say

class SomeClass<O extends Number>

Upvotes: 1

Related Questions