Let's say I have this Java code (midterm review!):
public class A {
public int key;
}
public class B extends A {
}
public class Problem1 {
public static void f(A x) {
A y = x;
y.key = x.key + 1;
}
public static void f(B x) {
B y = new B();
y.key = x.key + 2;
x = y;
}
public static void main(String[] args) {
A p = new A();
p.key = 3;
B q = new B();
q.key = 10;
f(p);
f(q);
p = q;
f(p);
System.out.println(p.key);
}
}
I'm not sure I properly understand p = q. Here's my understanding thus far: because B extends A, this operation is allowed but it doesn't make p and q point to the same object. Rather, it updates the key value for p but it remains of class A. Which is why f(p) at the end returns 11. This doesn't follow with what I thought I knew about Java previously so an explanation would be appreciated.
For example if I have int a = 4 and int b = 3, then I do:
a = b;
b++;
return a;
a will return 3, even though it should be pointing to the same thing that b is pointing to?
Please advise.