Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java compiler decide whether you can call a method based on the “reference” type and not on actual “object” type?

Tags:

java

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)?

like image 218
user3727850 Avatar asked Aug 30 '14 09:08

user3727850


2 Answers

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.

like image 54
TheLostMind Avatar answered Sep 19 '22 10:09

TheLostMind


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.

like image 42
Dennis Traub Avatar answered Sep 22 '22 10:09

Dennis Traub