0

"The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time."

Why not at compile time? I can't understand why the compiler can't figure out which method is suppose to be called. It's not like a new method will be invented at runtime or anything. All the instructions of the program are available for the compiler (obviously), so what's the deal???

Thanks.

2
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

Suppose class B extends class A and overrides its doIt method. Consided this pseudo code

A myObject;
while ... {
    ask the user a question
    if (user reply is "A")   myObject =- new A();
    else  myObject = new B();
    myObject.doIt();  // sometimes this is A's version, sometimes it's B's
}
0

Here's another example that often happens in graphics apps (pseudo-code):

ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Circle...
shapes.add(new Square...
shapes.add(new Triangle...
...
for (Shape s : shapes) {
   s.paint(...  // different paint method for every kind of Shape
}
0

I forgot the definitive example...

ObjectInputStream in = ... some file or TCP/IP connection
Object o = in.readObject();  // could be absolute any kind of Object
print o.toString();          // which toString version to use?
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.