Home difference between inheritage and creating new object

# difference between inheritage and creating new object

Gregory
1#
Gregory Published in 2017-12-07 22:00:57Z
 I have a question. What is the difference between these two: class Machine { int x = 2; } class Car { public void start(Machine abc){ abc.x = 10; } }  And: class Machine { int x = 2; } class Car extends Machine { public void start(){ x = 10; } }  I know that in the first example I'm creating kind of new object (am I right?) in Car class and I can use variable x from Machine class, and in the second example I'm inheriting from class Machine to class Car, so I can use variables from Machine in Car. But I don't know when should I use first one and when the second one, which is better, and so on. Could someone explain me the difference?
Przemysław Moskal
2#
Przemysław Moskal Reply to 2017-12-07 22:41:56Z
 In the first example you say "I want Car to assign a value of 10 to some Machine's (Car isn't really connected with that Machine, it could be "Gate", "Garage" or other classes that Car can cooperate with Car, but they are not in the relation "Car is a..." ) variable x" In the second one you say "Car is a machine and I want it to be able to change value of it's own x variable to 10". (You could say "I want my car to start its own engine, for example). I know that in the first example I'm creating kind of new object (am I right?) - it's not about creating new Machine reference by passing it as an argument. You rather say that you want instance of Car class to be able to change x value of the one specific instance of Machine class. Not to all Machines, just to the one you pass as an argument to the start() method. Example: myFerrari.start(gateThree) Car has a functionality to open the gate when you want it to, but Car is not a Gate. But I don't know when should I use first one and when the second one, which is better, and so on. In the second example you say Car is a Machine - so it is able to perform all actions that Machines are able to perform and it also is able to perform some actions specific only to Cars and not to all Machines. To use inheritance you should be sure that you can say Car is a Machine.
Nattydredd
3#
 The first is sometimes called a 'Uses a' relationship, as in 'the car uses a machine', while the second is sometimes called an 'is-a' relationship, as in 'the car is a machine'. This second relationship is called inheritance.. There is a third broad type, the 'has-a' relationship that you've not shown here: class Machine {} class Car { Machine machine; }  The first relationship is a lot easier to understand than the second. Typically we only model the second if we want to substitute one sub-class (Car in your example) with another derived from the same parent (Machine).