Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

oop - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a big plus on declaring them using the interface, which is what is known as "coding to an interface" instead of "coding to an implementation" which is a big Object Oriented Design (OOD) principle, this way you can declare a method like this:

public void (IVehicle myVehicle)

and this will accept any object that implements that interface, then at runtime it will call the implementation like this:

public void (IVehicle myVehicle)
{
    myVehicle.run() //This calls the implementation for that particular vehicle.
}

To answer the original question, why would you use one over the other there are several reasons:

1) Declaring them using an interface, means you can later substitute that value with any other concrete class that implements that interface, instead of being locked into that particular concrete class

2) You can take full advantage of polymorphism by declaring them using an interface, because each implementation can call the correct method at runtime.

3) You follow the OOD principle of code to an interface


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...