![]() That design works pretty well in the real world. This interface only you gives you access to the operations that are required to brew a coffee and hides every other detail. You always use them via the interface of the coffee machine. You also don’t interact with them directly. In the real world, these two elements are parts of the coffee machine and can’t be separated. The CoffeeMachine class models a modern coffee machine with an integrated grinder and a brewing unit. I use composition in the CoffeeMachine project that you might already know from the previous posts of this series. They can only use it via a public class that uses the package-private class in a composition. External clients of your software component are not aware of this class. This class can’t be accessed outside of its own package and is not part of the API. If you use no access modifiers for a class, it becomes package-private. If you want to allow external access to an attribute, you need to implement a getter or setter method for it.īut that’s not the only thing you can do to create a clean API. It’s a common best practice to use the private modifier for all attributes, including the ones that reference other objects, so that it can only be accessed within the same object. When you compose a class, you can decide if the referenced classes become part of the API or if you want to hide them.Īs I explained in my article about encapsulation, Java supports different access modifiers. This also enables you to design clean and easy-to-use APIs. You can do the same in software development when you design a class to keep a reference to an object and to use it in one or more of its methods. ![]() The car and the coffee machine integrate an engine, grinder and brewing unit via their external APIs to compose a higher level of abstraction and provide more significant value to their users. And a coffee machine has a grinder and a brewing unit, but it is none of them. The concept of composition is often used in the real world, and it should be the same in software development. That allows stronger encapsulation and makes your code easier to maintain as Joshua Bloch explains in the 3rd edition of his book Effective Java. The main reason to use composition is that it allows you to reuse code without modeling an is-a association as you do by using inheritance.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |