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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT 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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sharon SethCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.