"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.

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
}

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
}

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?
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.