What is a virtual method in Java, and does Java require a special keyword to declare one?
A virtual method is one where the runtime picks which version runs, based on the actual object. In Java every instance method is virtual by default, so there is no keyword to write.
public class Main {
public static void main(String[] args) {
Shape s = new Square(4);
System.out.println(s.area()); // 16
}
}
And here is the parent and the child.
public class Shape {
public double area() {
return 0;
}
}
public class Square extends Shape {
private final double side;
public Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
So the method area in the parent is virtual, and it means the runtime picks the version. And the child has overridden it, so the Square version runs.
And the ways to stop a method from being virtual are three. A static method is not virtual, because it belongs to the class. A private method is not virtual, because it cannot be overridden. And a final method is not virtual, because the language forbids overriding it.
the kind is it virtual
---------------------------- ----------------------------------
a normal instance method yes
a static method no
a private method no
a final method no, it cannot be overridden
And there is one more thing worth knowing about, and it is about the @Override annotation. It is not what makes the method virtual, the method is already virtual. The annotation is a safety check that tells the compiler to check that the method really does override one, so a typo in the name or the parameters is a compile error.
So the rule to remember is this. Every instance method in Java is virtual unless it is static, private or final.
The next two questions in this topic are about other languages and about final.