Reputation: 28081
Let's say I have an interface A
with generic type:
public interface A<T> {
T getT();
}
and a class B
implementing it:
public class B implements A {
public Integer getT() { return 1; }
}
...but without give it a type parameter.
What happens here? Does the A
be infer to A<Integer>
? Is it possible to force user to write type parameter with implements
statement(like B implements A<Integer>
)?
Upvotes: 7
Views: 3117
Reputation:
Your Question:
What happens here?
Since you left out the generic type, the system inferred it to be Object
. You could have done the following with the same results:
public class B implements A<Object> {
...
}
Next Question:
Is it possible to force user to write type parameter with implements (like B implements A)
Yes. This is how:
interface A<T extends Integer>
Hope this helps.
Upvotes: 7
Reputation: 1
What happens here? Well,because Integer extends Object ,so it will work fine , suggest you add parameter with implements
Upvotes: -1
Reputation: 27336
What happens here?
Well, because you've left the interface implementation as the raw type, the return type must be of type Object
. It doesn't infer the return type, but if your return type is of type Object
, which is every single object in Java, then it will work fine.
Is it possible to force user to write type parameter with implements statement(like B implements A)?
Force the user to type it? Computers are powerful, but mind control is a little way off yet.
Upvotes: 1
Reputation: 115328
Well, the "right" way to implement class B
is:
public class B implements A<Integer> {
@Override
public Integer getT() {
return 1;
}
}
Once you are writing the class B
this way you enforce user to use this class with Integer
type only.
When the generics specifier is missing (as in your example) the code is compiled (because generics are erasures) but most IDEs produce warning (e.g. in Eclipse the warning is "A is a raw type. References to generic type A should be parameterized B.java"
Upvotes: 1