interface class instance or implementation class instance?


When you want to create an instance of implementation class, do you assign it to the interface class or the implementation class?
Can't remember reasons why you do this way.
Can you explain or point to the web site?

What's the right way to create the instance of impletation class?

interface BankDao {


class BankDaoImpl {


clas TestBank{

BankDao bankDao = new BankDaoImpl();

BankDaoImpl bankDao = new BankDaoImpl();

Open in new window

Who is Participating?
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
You generally try and use 1) as much as you can. But sometimes you need to use 2) if the implementation class has more functionality than specified in the interface that you need to use.

The reason why you try and use 1) whenever you can is so that, if at a later time you need to have a different implementation, you can just change the class after the "new" keyword and you don't have to go and change everything else.
Sharon SethConnect With a Mentor Commented:
And the underlying principle you want to remember is  -
Code to an interface , not to the implementation
When you code to a specific implementation , you are locked to use only that implementation eg : In 2) , bankDao is locked down only to be a  BankDaoImpl.
In 1) bankDao  can be any one of the many  implementations
dkim18Author Commented:
Thanks. Now it is coming back to me.
käµfm³d 👽Commented:
Code to an interface , not to the implementation
In that well-known quote, the term "interface" does not necessarily mean a Java interface. It can also mean an abstract class.
Sharon SethCommented:
Right , interface in that quote means a higher level class . So you should always code to the highest level class possible , not to a specific subclass
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.