I was just wondering why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type? To explain I would like to quote an example:
class A {
void methA() {
System.out.println("Method of Class A.");
}
}
class B extends A {
void methB() {
System.out.println("Method of Class B.");
}
public static void main(String arg[]) {
A ob = new B();
ob.methB(); // Compile Time Error
}
}
This will produce a Compile Time Error that method methB()
not found in class A
, although Object Reference "ob" contains an object of class B
which consists of method methB()
. Reason for this is that Java Compiler checks for the method in Class A
(the reference type) not in Class B
(the actual object type). So, I want to know whats the reason behind this. Why does Java Compiler looks for the method in Class A why not in Class B(the actual object type)?
Assume that you have an Animal
class and a Dog
class which extends Animal
. Now, if Animal defines a method named speak()
and Dog defines a method named bark()
. If you do something like this :
Animal a = new Dog();
It means you are pointing to a Dog and saying that it is an Animal. When you look at a Dog as an Animal (and not as a Dog), you can only call methods which are defined for an Animal, not for a Dog.
During compilation, the compiler checks if a method being called is defined in the reference type.
By declaring the variable to be of type A you essentially hide the fact that it actually is a subtype. Not seeing the methods of type B is standard behavior which is essential in (strictly typed) object orientation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With