当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Casting an instance of a generic class into another whats the use?

问题描述:

I know this is possible but whats the use? Since it can only cast the same type as the object being casted?

class Example<X>{

//statements

}

//then this is declared

Example<Integer> x = new Example<Integer>();

//This is allowed

(Example<Integer>) x;

//this is not allowed, so what's the use?

(Example<Long>) x;

网友答案:

I see some use in the first one. Since java decides the type on runtime, in this particular case you could declare x like an instance of object, and by downcasting it in that line, you're telling the compiler that x is, indeed, Example.

I think the second one is not allowed in your example because Long is not an subclass of Integer, is more like a brother, since I think both inherit from Number.

Check the docs: Long || Integer

So, if you had done something like:

Example<Number> x = new Example<Number>();

(Example<Integer>) x;
(Example<Long>) x;

And then if you dropped your x in something like a visitor, with overloading, your x would've falled inside your Example<Long> implementation instead of your Example<Integer> implementation.

Guess I got a little bit confusing in there, but hope it helped.

网友答案:

The quote of the book does not say that you express by example. The book says that you can simply apply the normal rules for casting, as long as the type arguments are the same.

网友答案:

so what's the use?

There are lots of uses.

For example, for casting a wildcard parameter to a specific parameter, or more specific wildcard parameter:

Example<?> x;
Example<? extends Number> y;
Example<Integer> z;
y = (Example<? extends Number>)x;
z = (Example<Integer>)x;
z = (Example<Integer>)y;

or for casting the actual class to a more specific one:

Example<Integer> x;
SubExample<Integer> y;
y = (SubExample<Integer>)x;
分享给朋友:
您可能感兴趣的文章:
随机阅读: