Your code is effectively doing
Ford myFord; // a a;
BlueFord yourFord; // b b;
myFord.printMileage(); // a.print();
yourFord.driveAndPrintMileage(); // b.print(); <- does more than printing!
myFord.printMileage(); // a.print();
There is no reason why myFord
's mileage should change when yourFord
is being driven. They are the same kind of car (a Ford
, with the latter being the special blue edition), but they are not the same car (one is yours, one is mine). Driving one doesn't change the mileage of the other.
You use the same name for the type (Ford
) and the instance (myFord
) of each class/variable. Those are fundamentally different things and giving them the same name doesn't make them one and the same thing (it just makes things more confusing for you).
Making i
a static
variable would "sync" it between all the instances - it's as if each Ford
car was always connected to the internet and broadcasted changes to i
to all other Ford
s. Imagine static int i
as a "total miles driven by all (blue) fords ever" counter. But note that a static
variable no longer lives in one of the instances (it's not stored in each Ford
) but somewhere centrally (some Ford company server).
But the entire idea of object oriented programming is getting rid of global state (which includes static
variables) and have each instance manage its own state. I don't want my Ford
to talk to all other Ford
s constantly, relying on some external connection.