Java Magazine, Sept/Oct 2017
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2017 82 fix this because unlike the collections arrays know their base type That is if you try to store a Parent object in an array of Child youll get an exception specifically an ArrayStoreException Its better perhaps if the compiler can help you avoid ever making the mistake but a reliable exception when you perform the insertion is probably acceptable even though allowing an inappropriate object into the collection is not Because of this Java has always permitted the call pairing described in option A and that option is correct However in the generics mechanism and therefore in the Collections API theres no such runtime safety If the compiler cant prove safety the generics system must refuse to compile the code But a workaround is provided by the generics syntax By using the List syntax you can say I dont know exactly what this will be a list of but and then fill in what you do know So what do you need to know for this to work Whats happening is that youre reading objects that is whatever the question mark represents in this particular situation youll be reading that type of object and then assigning those objects to a variable of type Parent This assignment happens in this case in the for loop assigning to the variable p What can the question mark represent if you want to be able to safely assign objects of that type to the Parent reference Anything that is Parent or a subtype of Parent therefore you can express this using the List extends Parent syntax Because of this option C is correct Option D might look plausible but the pairing can be used only in a method that stores Child objects into the list that is passed as the argument This form fails in a method that assigns the contents of the list to any type other than Object this is because super Child might be a list of literally anything thats a parent class of Child including Object So given this method body option D is incorrect Option E creates the same possibility of inserting a Parent object into a List thats not ready to accept it Because of this option E is also incorrect article Simon Roberts joined Sun Microsystems in time to teach Suns first Java classes in the UK He created the Sun Certified Java Programmer and Sun Certified Java Developer exams He wrote several Java certification guides and is currently a freelance educator who teaches at many large companies in Silicon Valley and around the world He remains involved with Oracles Java certification projects
You must have JavaScript enabled to view digital editions.