If I have two classes, A and B,
public class A {
public int test() {
return 1;
}
}
public class B extends A{
public int test() {
return 2;
}
}
If I do: A a1 = new B(), then a1.test() returns 2 instead of 1 as desired.
Is this just a quirk of Java, or is there some reason for this behavior?
No, that is correct (it is due to polymorphism). All method calls operate on object, not reference type.
Here your object is of type
B,so test method ofclass Bwill be called.