I had a exam for a course named “Java for Android I” earlier today and found this question that I just don’t get. Maybe some of you could explain it for me.
Question:
View this collection ArrayList p. A class Person is a
superclass to Student. ArrayList implements the List-interface
(according to the Java-API).The compiler wont allow some of the situations noted in the code. Why?
Describe how they may entail that p wont contain instances of Person
or why p is not a ArrayList . E.g. p.add(“Hello”); now
contains a String instance.
Code:
p = new ArrayList<Object>();
void method ( ArrayList<Student> als) { ... }
void method ( List<Person> lp ) { ... }
void method ( ArrayList<Object> alo) { ... }
How would you describe this question? I just don’t get what my professor want’s me to answer.
Sorry if the quote has messed up grammar. I’ve been translating it from swedish.
Your professor’s question is about the basics of type checking in Java generics. Assuming:
This is a valid snippet:
as is this:
This is obviously not valid, because an object can be a
Personinstance without being aStudentinstance:But this is my favorite – it always trips people up:
This is an invalid snippet. “What? Why!” I hear you ask. Well, it’s true that all
Studentobjects are also instances ofPerson, so that assignments like this work:When it comes to parametric types, though, the Java compiler does its best to protect you. Imagine this piece of code:
If the compiler did not object to the assignment, it would be now possible to enter
Personobjects to anArrayListthat only hostsStudentobjects…Method calls work in exactly the same way. Just strip the type of the argument from the method signature and try to imagine an assignment to that type…