Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Spring with Hibernate Getting Started with CRUD in Spring + Hibernate Saving Entities

Why is the method being called from the interface instead of the implementation?

I'm a little confused as to why inside the save method of CategoryServiceImpl class we're calling the save method from the CategoryDao Interface. I thought (and I may be mistaken) that we get the methods from the implementation. So instead of the method save being called from the CategoryDao shouldn't have it been called from CategoryDaoImpl?

PJ Pollina
PJ Pollina
8,012 Points

I haven't done that particular course on here so I'm not entirely sure, but I think it's a case of polymorphism? If you could post your code I might understand the context of the question better.

1 Answer

Boban Talevski
Boban Talevski
24,793 Points

There are several things to understand here.

First and foremost, you simply can't call an interface method if it isn't implemented somewhere. Or to put it another way, a class that implements a certain interface must implement all methods from the said interface or the class won't compile. So, be sure that we are actually calling the implemented method in this case.

Now on to the details for this particular case. The CategoryDao object we have in the CategoryServiceImpl is Autowired to get an instance of a class implementing the CategoryDao interface, it can't instantiate an object of an interface. And it's the way Autowired works, put an interface as the type and then Spring looks for a class which implements that interface to instantiate the actual object from. The class which implements the particular interface also needs to be annotated with Repository (or any other Spring component). So, since there's only one such class, which is CategoryDaoImpl, the object we have is an instance of that particular class.

So what happens behind the scenes looks something like this:

CategoryDao categoryDao = new CategoryDaoImpl();

And when we call methods on that categoryDao object, we are actually calling the method implementations from CategoryDaoImpl.

Thank you so much your answer really helped clear things up!

Boban Talevski
Boban Talevski
24,793 Points

You are welcome. Glad it helped clear things up! :)