A
A
Andrey Andryushchenko2015-06-10 15:23:19
Java
Andrey Andryushchenko, 2015-06-10 15:23:19

Casting types inherited from Number?

There is a generic class of the form ClassName<TYPE extends Number>, in which it is necessary to cast different classes of the ClassName type, for example, ClassName<BigInteger>and ClassName<Long>. There is also a class for describing fractions, inherited from Number. That is, you may need to lead ClassName<ImproperFraction>to ClassName<Double>. So, how do I properly cast object generic types in Java?

public class ClassName<TYPE extends Number> {
//govnokod
    public <T extends Number> ClassName<T> count(){
        return this;//пишет incompatible types: requred ClassName<T>, found ClassName<TYPE>
    }
//govnokod
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
angry_cellophane, 2015-06-10
@angry_cellophane

1. First, nothing is said about the relationship between TYPE and T.
2. Secondly, there is no covariance and contravariance in Java due to type erasure. Example: Class < Integer > is not a subtype of Class < Number > . Nice link to wikipedia.

C
Copperfield, 2015-06-10
@Copperfield

public class ClassName<TYPE extends Number> {
        //govnokod
        public <T extends Number> ClassName<TYPE> count(){
            return this;//пишет incompatible types: requred ClassName<T>, found ClassName<TYPE>
        }
//govnokod
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question