Maulik
Maulik

Reputation: 19418

When should I use an interface vs an implementation when declaring a new object?

I am new to Java. I want to know when should we use base class's reference and when we should create a new object. I mean we can write

List list = new ArrayList();

and when

ArrayList list = new ArrayList();

How to determine what to use ???

Upvotes: 3

Views: 6008

Answers (4)

Richard H
Richard H

Reputation: 39055

Often it doesn't matter. An interface just defines a set of methods that you can call on an object: that is the object implements an interface. When it does matter is when you might have multiple implementations of an interface. Let's say you have a method that does something with an object that implements the Vehicle interface:

public static double getSpeed(Vehicle vehicle) {
    return vehicle.getSpeed();
}

You want to pass around the interface as you don't care whether the object is a car or a van or whatever, and you want this method to work for all implementations of this interface - ie all types of vehicle. They all implement the Vehicle interface so you know you can call the getSpeed() method. If you did this:

public static double getSpeed(Car car) {
    return car.getSpeed();
}

then your method wouldn't work for vans or lorries, even though they both implement the Vehicle interface and as such both have .getSpeed() methods.

Upvotes: 2

asgs
asgs

Reputation: 3984

It's ok to use both, but the former is preferred because it's always better to call an implementation's method using a reference to the Interface or super type (List). The former doesn't depend on the implementation and eliminates the need to change the code when the implementation (ArrayList) changes, but the latter requires you to change the code when the implementation changes to anything other than ArrayList.

Upvotes: 8

user467871
user467871

Reputation:

Addition to @Jigar my advise is to use that way for type safety

List< T > list = new ArrayList< T >();

Upvotes: 4

Jigar Joshi
Jigar Joshi

Reputation: 240898

use

List list = new ArrayList();

Always learn to program with interface. tomorrow you can have new implementation

Upvotes: 5

Related Questions