Reputation: 7883
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 sumStringToInt extends SumFunction{
public int op(int num, String s){
return s.length() + num;
}
}
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
is it possible in Java inherit without instantiaion of Base class?, thanks in advance
Upvotes: 0
Views: 159
Reputation: 9614
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
.
Upvotes: 0
Reputation: 64650
public class sumStringToInt extends SumFunction<Integer, String>
{
@Override
public Integer op(int num, String s)
{
return s.length() + num;
}
}
Upvotes: 1
Reputation: 6249
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
.
Upvotes: 1
Reputation: 9265
Should be
public class sumStringToInt extends SumFunction<Integer,String>{
public Integer op(Integer num, String s){
return s.length() + num;
}
}
Upvotes: 4
Reputation: 24517
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...
Upvotes: 5