The out put should be 9 Accelerate : SportsCar, but When i run the above code it is printing 8 Accelerate : SportsCar, Can some body please clarify me on this? ps: Please use the [ code ] opening and closing tags (without the spaces) when posting source code. Thanks. - satya [ February 09, 2002: Message edited by: Madhav Lakkapragada ]
Joined: Nov 16, 2000
Ok this is easy. The way this works is as follows: In java the variable values are selected at compile time and the object is dynamicaly chosen(ie at run time). In th case the variable value selected would be 8 as it is at compile time and the the method that would be run would belong to SportsCar as it is chosen at run time. I hope thai amkses it clear. Let me know if you have any more questions. Thanks, Hemal
Joined: Jan 07, 2002
Fields and methods behave differently between classes and their subclasses. Methods can be overriden, but fields are hidden. When you make a method call with a reference variable, as when you write c.accelerate() , the VM will make a polymorphic method call; that is, at RUN TIME, it will deterime what method to call based on the actual class instance that the variable c refers to. This is dynamic binding. However, fields don't work this way. When you make a reference to a field, as when you wrote c.gearRatio, it is determined at COMPILE time which gearRatio field will be accessed. In this case, the type of c determines which gearRatio field. Since c is defined to be of type Car, the compiler inserts code at compile time to access the gearRatio field of the Car class. At runtime, the fact that the object refered to by c is really a subclass of Car is not at all a factor. This is an example of static, or early binding. Static methods also behave in this manner. Just remember that ONLY instance methods are subject to polymorphic calls; all other members (fields, static methods) are subject to static binding at compile time.
Joined: Jan 28, 2002
Thanks a lot to Rob & Hemal. I am cleared.
Joined: Jun 03, 2000
"bkumar" Your name doesn't agree with the javaranch guidelines. Please take a moment and edit your profile after reviewing the guidelines at http://www.javaranch.com/name.jsp Please change your Publicly Displayed name to follow the guidelines. thanks for your cooperation - satya