class A2 {
int numt=111;
void hello() {
System.out.println("Hello from A2");
}
}
class B2 extends A2 {
void hello() {
System.out.println("Hello from B2");
}
}
class C2 extends B2 {
int numt=666;
void hello() {
System.out.println("Hello from C2");
}
}
class MethodOverriding2 {
public static void main(String args[]) {
A2 obj = new C2();
obj.hello();
System.out.println("Num is : " + obj.numt);
}
}
So basically the output here is
Hello from C2
Num is : 111
Why does it run hello() from C2 but numt from A2?
As I understand, I’m inheriting A2 into B2, and C2 into B2. Then in my main I’m creating an object of class A2 which refers to C2 (which it can do since A2 is a superclass of C2).
Then in compile time there is no error as the code is satisfied.
At runtime, the program looks for ‘hello()’ where ‘obj’ is referring to and not where it is defined.
But it does the opposite for ‘numt’. Why is this so? And is my above understanding correct? Please correct if it isn’t.
Thanks a lot! I know it’s a novice question, I’m very new to OOP.
When you call method, the method in the instance will be called, not on reference type due to polymorphism. Here your object is of C2 even though reference is of type A2, so method in C2 will be invoked.
When you access variables it is on reference type than object type because polymorphism doesn’t applicable for fields. That is why it is always good design to make your variables private so that other classes can’t directly access these variables.