Confusion in Java Generics
I'm beginner in Java, I'm trying to compile some small program, can somebody explain me, what is my problem, thanks in advance:
public abstract class SumFunction<Y,X> {
public abstract Y op (Y y, X x);
}
public class su开发者_Go百科mStringToInt extends SumFunction{
public int op(int num, String s){
return s.length() + num;
}
}
errors
Multiple markers at this line
- The type sumStringToInt must implement the inherited abstract method SumFunction.op(Object,
Object)
- SumFunction is a raw type. References to generic type SumFunction<Y,X> should be
parameterized
edited
is it possible in Java inherit without instantiaion of Base class?, thanks in advance
You are indicating that SumFunction<Y,X>
is taking two arguments.
Thus your class should look like this:
public class sumStringToInt extends SumFunction<Integer,String> {
public Integer op(Integer num, String s){
return s.length() + num;
}
}
Try that...
Should be
public class sumStringToInt extends SumFunction<Integer,String>{
public Integer op(Integer num, String s){
return s.length() + num;
}
}
You haven't specified the type parameters when extending SumFucntion
. sumStringToInt
needs to extend SumFunction<Integer,String>
.
Also, you can't use primitives in generics. So, use Integer
instead of int
.
public class sumStringToInt extends SumFunction<Integer, String>
{
@Override
public Integer op(int num, String s)
{
return s.length() + num;
}
}
You're missing the type parameters for SumFunction. Because of that the compiler assumes you want to use the raw type
which means Y
and X
use Object
as their type.
public class sumStringToInt extends SumFunction{
public int op(int num, String s){
return s.length() + num;
}
}
If you pass the types you want to use for SumFunction, this should compile. Like so:
public class sumStringToInt extends SumFunction<Integer, String> {
public int op(int num, String s){
return s.length() + num;
}
}
You may have noticed that we use Integer
instead of int
as the type. This is because you cannot use primitive types with generics. Luckily, there are wrapper Objects for each primitive type, in this case Integer
for int
.
精彩评论