Here is some example code of what I'm goofing up on all the time:
What will be the effect of compiling and running this class Test? Generates a Compiler error on the statement v= c Generates runtime error on the statement v= c Prints out:
A. Does not complie becasue the v=c assignment.
B. Generate a runtime error.
C. Prints out:
Vehicle : drive Car : drive Car : drive
D. Prints out:
Vehicle : drive Car : drive Vehicle : drive
The answer is 'C' and I put 'A'
I'm thinking the reference variable of type 'c' cannot be assigned to a reference variable of type 'v', because 'v' is a parent type and doesn't maybe have all the code/guts of the sub type 'c'.
How can I get this right in my mind. I know a object doesn't forget its type....
[HENRY: Added code tags and formatted code] [ November 21, 2006: Message edited by: Henry Wong ]
donald rieck
Ranch Hand
Joined: Mar 12, 2003
Posts: 75
posted
0
Oops, this came from "www.4Tests.com question number 15.
When you say v = c in the above code, you are doing Vehicle v = new Car(); which is perfectly legal to say. This just means that a superclass reference is pointing to a subclass object. Now when you invoke any methods using v, the method in the subclass is called if that method is overriden.....if not, the method in the superclass is called because the reference is of superclass type.
It dosn't compile simply because, the reference type is of class A and when you say A a = new Main() and do a.bMethod(), it checks for the method in class A which is not there, so it results in a compile time error.
marko salonen
Greenhorn
Joined: Nov 19, 2006
Posts: 8
posted
0
Originally posted by Jothi Shankar Kumar Sankararaj:
Originally posted by donald rieck: From your example above.
A a = new A(); Main m = new Main(); a = m;
"a = m" is the same as " A a = new Main();"
therefore:
It will call the Main method:
hence, print out "From subclass".
I really dont understand how this could be right. Method aMethod("2") is called for instance referenced by A which is Main. Main doesnt have aMethod(String) so superclass method is used instead. There fore outpu should be "2"
Andy Morris
Ranch Hand
Joined: May 30, 2004
Posts: 78
posted
0
In a previous post someone posted a good link to Polymorphism. I'd look for it and read it as it's very clear and should resolve your worries.
There you are. [ November 22, 2006: Message edited by: Andy Morris ]
Wil Guo
Greenhorn
Joined: Jan 09, 2006
Posts: 11
posted
0
Originally posted by Jothi Shankar Kumar Sankararaj: Hi Above,
It dosn't compile simply because, the reference type is of class A and when you say A a = new Main() and do a.bMethod(), it checks for the method in class A which is not there, so it results in a compile time error.
Jothi, According to the polymorphism link posted, java uses later-binding and should call method in child class, in this case, should call method in Main. Thanks!