Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose inheritance or interface to implement design pattern in Java?

I just want to inject some design patterns into my Java code, but I don't know which style to use -- is inheritance or interface preferred? And why?

like image 515
Summer_More_More_Tea Avatar asked Jan 19 '26 15:01

Summer_More_More_Tea


1 Answers

Design patterns aren't a thing to just randomly inject into your application. They're design-time sorts of things, not parmesan cheese that you sprinkle on your code after it's already baked.

That said, Josh Bloch's seminal Effective Java strongly encourages developers to use interfaces for shared behavior rather than using inheritance. This matches my own experience.

ETA: Among other reasons, if you're implementing an interface, you can easily create a mock of that interface for use in testing without worrying about the rest of the inheritance hierarchy.

like image 169
Jim Kiley Avatar answered Jan 22 '26 06:01

Jim Kiley