Saurabh Gokhale
Saurabh Gokhale

Reputation: 46395

Java - Virtual Methods

How does virtual functions work behind the scenes in Inheritance ? Does the compiler treat virtual functions specially ?

Upvotes: 17

Views: 42014

Answers (3)

user207421
user207421

Reputation: 310884

'Virtual' is a C++ term. There are no virtual methods in Java. There are ordinary methods, which are runtime-polymorphic, and static or final methods, which aren't.

Upvotes: 15

Kevin Crowell
Kevin Crowell

Reputation: 10180

All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.

Upvotes: 38

Andrew Hare
Andrew Hare

Reputation: 351506

Yes, virtual methods are treated differently by the compiler and the runtime. The JVM specifically utilizes a virtual method table for virtual method dispatch:

An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them. Objects belonging to type-compatible classes (for example siblings in an inheritance hierarchy) will have dispatch tables with the same layout: the address of a given method will appear at the same offset for all type-compatible classes. Thus, fetching the method's address from a given dispatch table offset will get the method corresponding to the object's actual class.

Upvotes: 13

Related Questions