The following code when run obviously prints out \"B1/A2/B2\". Now, is it possible for it to print \"A1/A2/B2\" instead (i.e. A#method2() should invoke method1() on A, not
Yes, you can do it. Define A in package a:
package a;
public class A {
void method1() {
System.out.println("A1");
}
public void method2() {
method1();
System.out.println("A2");
}
}
Define B in package b:
package b;
import a.A;
public class B extends A {
@Override public void method2() {
super.method2();
System.out.println("B2");
}
void method1() {
System.out.println("B1");
}
}
Put your test in package a and run it. The result is A1/A2/B2. Of course this is unhealthy: note the necessary omission of @Override on method1 - if you put it back in, you will get a compiler error:
method does not override or implement a method from a supertype