have an Animal class ( abstract class ) , a Dog class . Dog obviously inherited the Animal class .
Then there are :
ArrayList
ArrayList
These two certainly correct .
but the following two :
ArrayList
ArrayList
I tried it , eclipse is being given . I doubt obtained from the following reasoning :
Animal ani = new Dog (); ; ( 3 )
Dog dog = new Animal (); ; ( 4 )
The first obvious is right, because you can use a subclass to initialize the parent class ; second right because there is no Animal object.
back to the previous question:
doubt one : ArrayList
doubts II: The second error is because ArrayList
hope to understand how this is going to be available to answer , thank you ~
------ Solution ---------------------- ----------------------
this has nothing to do with the transformation .
ArrayList
you declare a collection can be kept Animal, so Zhu cat ah dogs, as long as both can be inherited Animal entered survival.
behind the new collection and you can only save dog, pigs and cats can deposit into it ?
So in this way will not work
So, in the use of generics , as long as both sides are used, it must be the same on both sides
In order to maintain the compatibility , but only on one side there is nothing wrong with generics .
------ For reference only ---------------------------------- -----
supplementary question : ArrayList
------ For reference only -------------------------------------- -
ArrayList
I suggest you look up and down the transformation of knowledge transformation , it should be almost the same.
------ For reference only -------------------------------------- -
Oh transformation of knowledge , good . Thank you ~
------ For reference only ------------------------------------ ---
add:
if you use wildcards , although it seems that the wording is not the same on both sides , in fact, essentially the same
like this is possible
ArrayList al = new ArrayList
------ For reference only ------- --------------------------------
upstairs +1 ....
---- - For reference only ---------------------------------------
generics are not require both types are the same as you ?
------ For reference only -------------------------------------- -
as Java, generics are not covariant .
没有评论:
发表评论