let's say i have class A
and class B
which extends A
,
here are the classes:
A:
public class A {
public int x;
public static int y;
public A(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public static int getY() { return y; }
public A get1() { return this; }
public A get2() { return new B(x, y); }
}
B:
public class B extends A {
public int x;
public B(int x, int y) {
super(x, y);
this.x = x*2;
this.y = y*2;
}
public int getX() { return x; }
public static int getY() { return y*3; }
public A get1() {
x++;
return super.get1();
}
public A get2() { return get1(); }
}
Here is the main function:
public static void main(String[] args) {
A a1 = new A(5, 10);
A a2 = a1.get2();
A a3 = a2.get2();
System.out.println("a1.x=" + a1.x);
System.out.println("a1.y=" + a1.y);
System.out.println("a2.x=" + a2.x);
System.out.println("a2.getX()=" + a2.getX());
System.out.println("a2.getY()=" + a2.getY());
System.out.println("((B)a2).getY()=" + ((B)a2).getY());
System.out.println("((B)a2).x=" + ((B)a2).x);
System.out.println("a3 is A: " + (a3.getClass() == A.class));
System.out.println("a3 is B: " + (a3 instanceof B));
System.out.println("a3==a2: " + (a3 == a2));
}
My problem is with the a2
and a3
objects,
a3
is basically a2.get2()
, after following the method it will reach the A
get1()
method that returns this
.
Since the method is found in class A
i was sure it will only return the reference to A
part of object a2
and not a reference to the whole object,
So when i try this line:
a3.getClass() == A.class
i will get True
.
When i debugged a3.getClass()
is "class B".
Can someone explain to me what the return this
line actually does when it's inside a father class?
Thanks!