I am trying to get to grips with interfaces and their implementation in Java.
I have an interface and 3 classes, 2 of which implement the interface. The implementation of the interface requires 2 methods,
toString()[which is using@Overidehere for Netbeans satisfaction] and-
wheelCount().public interface IVehicle {
@Override
public String toString();
public int wheelCount();
}
We then have the two classes Bike and Car.
public class Bike implements IVehicle{
@Override
public int wheelCount() {
return 2;
}
@Override
public String toString(){
String s = "This is a Bike with " + wheelCount() + " wheels!";
return s;
}
}
public class Car implements IVehicle{
@Override
public int wheelCount() {
return 4;
}
@Override
public String toString(){
String s = "This is a Car with " + wheelCount() + " wheels!";
return s;
}
}
Some other class called myClass contains a method to print stuff out… printStuf()
public void prntStuf(IVehicle myVehicle){
String s = myVehicle.toString();
System.out.println(s);
}
Assuming an instance of myClass is created, if somewhere in the code we create instances of Bike() and Car(), and we pass these objects into the method prntStuf, what would be the benefit in using either of these assignments.
IVehicle x = new Car()
IVehicle modeoftransport1 = new Car();
IVehicle modeoftransport2 = new Bike();
As opposed to… Car x = new Car()
Car modeoftransport1 = new Car();
Bike modeoftransport2 = new Bike();
Is there an actual difference or benefit or does it boil down to coding conventions?
From what I can tell, they both have the same effect, in that they both produce the same outcome. I’ve looked through previous questions on here and searched the web but can’t put my finger on it. Hope this makes sense.
In your example, the type of the variable doesn’t matter.
The choice of type is really a choice about what you’re going to do with the variable later. When you say:
You’re saying “I am going to be dealing with a new Car in ways where it matters that it’s a Car”; for example, if Car had some other, Car-specific, methods, maybe you’re going to call those. When you say:
You’re saying “I am going to be dealing with a new Car in ways where it doesn’t matter what kind of vehicle it is”.
So, yes, coding convention, or coding style, to a large extent.