Virtual functions

Say Dog is a subclass of Animal, and both class definitions include an implementation of the function noise. If you have Dog d = new Dog();, then clearly d.noise() should use the definition in Dog and not the definition in Animal, since the reference d and the object stored in it both have type Dog.

But if instead we have Animal a = new Dog(), then what does a.noise() evaluate to? Should it use the definition in Animal, since the reference a has type Animal, or should it use the definition in Dog, since the object referenced by a is in fact a Dog?

If the function is “virtual,” then it will use the definition in the type of the object (Dog). If the function is not virtual, it will use the definition in the type of the reference (Animal).

Abstract methods are always virtual, since there is only one definition anyway. Virtual methods may or may not be abstract.

In Java, all methods are virtual by default; there is no language keyword for it.

In C++, functions are not virtual by default, but they may be declared virtual in the base class. As mentioned above, a function declared virtual may or may not be abstract; i.e., it may or may not have an implementation.