1

How is it possible to define a variable type as an interface :

List<BigDecimal> filter = new ArrayList<BigDecimal>();

Shouldn't we define a variable by class or primitive data types and not an interface as follows :

ArrayList<BigDecimal> filter = new ArrayList<BigDecimal>();

How is it accepting interface variable definition?

maksimov
  • 5,792
  • 1
  • 30
  • 38
KAD
  • 10,972
  • 4
  • 31
  • 73

1 Answers1

1

In general, it's preferred to code to interfaces (your first example, declare the variable using the interface, not the class). That way, if you need to change to a different implementation, it's trivial to do that — you just change the new to something else, and nothing else needs to change, because you code to the interface.

The reason it works is that ArrayList<BigDecimal> implements List<BigDecimal>, and so is assignment-compatible with it. That means that a variable declared as List<BigDecimal> is allowed to haev a reference of type ArrayList<BigDecimal> assigned to it. It's a design feature of the language. This is fundamental to how interfaces, and indeed OOP in general, works in Java.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Well yeah it seems duplicate but the answer was good to clear the point. Sorry for the bad formatting at first i will make sure its better for next time. Thank you :) – KAD Nov 27 '14 at 18:38