tags:

views:

118

answers:

3

1) If i define a java method:

void ChangeObject (Object o)
{
 o = new Object();
}

And in my main program, i instantiate an object o and call ChangeObject with o passed in. Will o remain intact after this method is run?

2) If i have two class: Child and Parent. And child is a subclass of parent. Which of these two statements will compile, and why:

Child myChild = new Parent();
Parent myParent = new Child();
+1  A: 
  1. Yes. o is really a pointer to the object being passed in. Essentially what happens is a copy of that pointer is made when it is passed in. Your method changes the copy of the pointer to point at the new object, but the original pointer (that was passed) is unchanged.

  2. The second statement will compile. The first will not. Think of inheritance as "substitutability". When you say "class Child extends Parent", you are saying "I can give a child to anything that needs a parent because child is substitutable for parent". The reverse is not true. Parent is not substitutable for child.

SingleShot
Regarding 1. Even if my method "copies" the pointer, but the pointer is really just a "memory address". so even if you copy down the memory address, it still can't prevent you from changing what that address points to, right?
Saobi
I hope I am not making this more confusing :-) "Pointers" are not memory addresses in this sense - they "point" to memory addresses (thus the name). When you assign the new object to the copy of the pointer, the pointer changes what it points at - it now points at the new object. The original pointer still points at the original object because it was never changed.
SingleShot
+1  A: 

ad 1) The object will stay intact, since you pass in a variable, containing a reference to the orginial object. If you give the variable a new value, the old object will not be affected.

ad 2) The second Line will compile, since Child is also a Parent. The first does not since Parent is not a child.

Dominik
+1  A: 

Seems like the time you took to ask this question could have been spent answering it for yourself.