Roxana
Roxana

Reputation: 1581

Warning in java abstract generic method

I have something like:

public abstract class Base{
    public abstact T <T> method();
}

public class ExtendingClass extends Base{
    public SomeObject method(){
    }
}

However, ExtendingClass#method has the warning Type safety: The return type SomeObject for method from the type ExtendingClass needs unchecked conversion to conform to T from the type Base

Can you please tell me why is this and how should this be handled?

Upvotes: 2

Views: 211

Answers (2)

Sachin
Sachin

Reputation: 3554

abstract class Base <T> {
    public abstract T method();
}



public class test extends Base<String>{

    @Override
    public String method(){
        return null;

    }
}

When you are writing the concrete example you must pass proper value for it so that compiler can verify the value during compilation

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19284

you can use:

public abstract class Base<T> {
    public abstract T method();
}

and:

public class ExtendingClass extends Base<SomeObject >{

    public SomeObject method(){
        ...
    }

}

This happens because the generic parameters don't appear anywhere else except in your abstract method declaration.

This method signature is almost equivalent to public abstract Object method().

From java generic methods tutorial:

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.

Upvotes: 3

Related Questions