I'm trying to understand late binding. And searched results: Late Binding: type is unknown until the variable is exercised during run-time; usually through assignment but there are other means to coerce a type; dynamically typed languages call this an underlying feature, but many statically typed languages have some method of achieving late binding.
and example is like this:
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
@Override
public void start() {
System.out.println("Inside start method of Car");
}
}
But what's benefit Vehicle vehicle = new Car(); using this. Should just write Car car = new Car(); ? Please explain to me?
Yes you could do that. In this tiny example, there is little immediate benefit in late binding.
But what about this slightly different example?
... or if we add more subclasses of
Vehicle
, and (say) instantiate aCar
or aTruck
...There are other benefits too, that will become clearer to you as you gain experience in programming, especially as you have to write and maintain larger programs.
For the record, Java is generally classified as a statically typed language. And the polymorphism / late binding in both your example and mine is relying on static typing. Dynamic typing only comes into play if we use type casts,
instanceof
and similar.The distinction between static and dynamic typing is about when the type checking happens. If the type checking happens (mostly) at compile time and the errors are reported at compile time, then the language is statically checked.
We could also add more subclasses of
Vehicle
, and modify themain
method to create and start any kind of vehicle, without mentioning the names of the subclasses in the source code formain
. That's another aspect of late binding that is not evident in your example.