Say you have an arrayList of objects ArrayList<Object> arr = new ArrayList<Object>();
and you then fill this arraylist with several different objects, all of which inherit from object
.
arr.add(new Integer(1));
arr.add("Im a String");
arr.add(new SomeOtherObject);
Say you then loop through the arrayList calling the .toString()
method, this will actually work as expected, calling the overridden toString()
methods of the String
and Integer
classes, what confuses me is that to the JVM, the Integer
and String
objects inside of the arrayList were implicitly casted into objects, so how in the world does the JVM know to caste them back into whatever they were before they were put into the arrayList? Sorry if this question has an obvious answer, but this doesnt seem to make much sense to me
each object has it's type stored in the header of that object. When you cast a reference to an object, this doesn't alter the object in any way.
When you call
.toString
for example, it looks up the method to call from the classes' description. NOTE: It doesn't have to do this every time if it can optimise the code.