In that example, I don't think you can talk about an advantage (or disadvantage), because your two lines of code each do something very different.
If the type of variable a
is A
, then a.b
refers to the field b
with the value 10
.
But if you change the type of a
to B
then a.b
refers to a totally different field, the one declared inside B
, with the value 12
.
If instead b
was a method, then the one declared in B
would "override" the one declared in A
, which is a very different situation. e.g.
class A
{
public int b() { return 10; };
}
class B extends A
{
public int b() { return 12; }
}
And the calling code would be:
A a=new B(); //line1
//B a=new B();//line2
System.our.println(a.b());
That is, we call the method b
to get the return value. Now it makes no difference to the behaviour whether the type of a
is A
or B
. What matters is the type of object that a
refers to, which is always B
and hence always has the behaviour defined in B
, so it will print 12
regardless.
The advantage of this is that you can have a collection of objects (e.g. various kinds of vehicle) and they can be a mixture of cars, boats, trains etc. Each has its own implementation of the start
method, so you can treat them all the same way.
Although generally it's clearer to define such methods in an interface
, rather than a class
. There is no general way to start
a vehicle, so no reason to have a base class that has a meaningless implementation of start
. Instead you just use an interface to declare the "shape" of the method without giving it any implementation.