Skip to content
Advertisement

Why would you declare an Interface and then instantiate an object with it in Java?

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.

The example code my friend showed me contained this:

IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();

Where IVehicle is an interface that’s implemented in both the car and bike classes. When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:

Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();

So, my question is – why would you use the former method over the latter when declaring and instantiating the modeOfTransport objects? Does it matter?

Advertisement

Answer

It doesn’t matter there.

Where it really matters is in other interfaces that need to operate on IVehicle. If they accept parameters and return values as IVehicle, then the code will be more easily extendible.

As you noted, either of these objects can be passed to a method that accepts IVehicle as a parameter.

If you had subsequent code that used Car or Bike specific operations that were used, then it would be advantageous to declare them as Car or Bike. The Car and Bike specific operations would be available for each of the relevant objects, and both would be usable (i.e. could be passed) as IVehicle.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement