so i was trying to understand the interfaces, but i almost only see articles that explains “how” to use the interface, my problem is to understand the “why” :
so it’s better to use Interface than creating and subclassing a class, which might be useless,
so we implement the interface methods in the class, but i don’t understand why this is a good thing,
Let’s say :
a class like Car.java defines all the code to make the car
we create the interface Working.java with several methods like start(), stop(), etc.
we implement the methods in Diesel_Car.java, Electric_Car.java, etc.
so what does it change for Car.java? This might not be the best example, as it seems that Car should be the parent of Diesel_Car.java etc,
but what was the meaning to implement the methods in those classes?
Is there a method in Car.java that somehow “calls” the Diesel_Car.java class and its interface methods?
I’ve read that the interface is like a “Contract”, but i only see the second part of this contract (where the method is implemented) and i’m having some trouble to imagine where the first part happen?
Thanks for your help
Lets take your example of a Base class of
CarwithElectric_CarandDiesel_CarSubclasses, and expand the model a bit.Car may have the following Interfaces
Working: withstart()&stop()methodsMoving: withmove(),turn()&stop()methodsThe
Carmight contain an instance of classAirConditionerwhich should also implement the interfaceWorking.The
Driverobject can interact with objects than implementWorking, the driver canstart()orstop(). (The driver can start or stop the car and the A/C seperatly).also, since the
Drivercan walk around on his own (and does not always need a car) he should implement the interfaceMoving.The object
Groundcan now interact with anything that implementsMoving: either car or driver.