Hi Dario
But even before runtime, should the compiler not be able to figure out that the c points to an object of type Car, simply based on the declaration where it is instantiated.
Thats the exact problem compiler faces.
Consider a super/sub classes as,
class Parent {
}
class Child1 extends Parent {
void method1() {}
}
class Child2 extends Parent {
void method2() {}
}
class
Test {
public static void main(
String[] args) {
Parent p1 = new Child1();
p1.method1(); // line-1
p1 = new Child2(); // line-2
p1.method2(); // line-3
p1.method1(); // line-4
}
}
The above code won't compile in java but assuming it compiled,
On line-1 if the compiler applied the logic you suggest then it would identify that "Oh, this is Child1 object and there is method1() in there" so its valid...Now, on line-2 we reassign p1 to Child2() object so on line-3 is now valid as there is method2() in Child2 but line-4 becomes invalid, right?
What should compile do here?? Should it warn user or what?
You might be wondering why I declare Parent's object instead of just Child1/Child2 but this is the essentially case when we are having Interfaces and we want to hide the implementing class names from the client's. We do,
interface I {
public void doThings();
}
Class A implements I {
public void doThings() {}
}
Class B implements I {
public void doThings() {}
}
Class Test {
psvm(String[] s) { // this isn't valid in java but I have used a short cut for main
I i1 = Class.forName(s[0]);
i1.doThings();
}
}
where s[0] can be "dynamically" assigned when we run the program. Here, Class.forName() loads the class specified by s[0] name and then calls method doThings() on it but it doesn't have to know whether the class is A or B...so this kind of "hiding" and declaring "Parent's object" is necessary sometimes...
I guess I'm not able to explain this but if you ever tried to write your own compiler you would immediately know "why the hack we have to declare things"...
Regards
Maulin