I got this from a berkley cs data structures webcast:
class A {
void f() {System.out.println("A.f");}
void g() {f();}
// static void g(A y) {y.f();}
}
class B extends A {
void f(){
System.out.println("B.f");
}
}
class C {
static void main (String[] args){
B aB = new B();
h (aB);
}
static void h (A x) {x.g();}
//static void h (A x) {A.g(x);} what if this were h
}
Can you tell me what prints out and why? The instructor said B.f but I do not understand why. I thought it was A.f. Thank you (no, I am not in the class, just trying to learn.)
edit: sorry for the mistakes I was copying it from a video lecture.
The reason “B.f” prints is because the implementation of a method is determined by an object’s run-time type, not its compile-time type. It’s like the
virtualkeyword in C++.Once you construct a
B, you know that calling itsfmethod will print “B.f”, even if theBis being referred to as anA.Also, your
A.fmethod is missing a close brace.