7.3 Composition
Hello everyone as agreed we will see the composition. Composition is essentially a way for you to refer to another object in your class. Once again, the simplest way is to make an example. So, we will create two classes, dog and human. In the dog class, basically what I want to do is establish a relationship between our dog and the human. So, the first thing I want to do is create a private property, so private String name each named dog and now what I want to do is say that each dog belongs to a human. And how do you do that? Well, remember that a class can be instantiated like that. So, private Human owner, and constructor Alt + Insert The next thing I want to do is create a "toString" method for this public class String toString() "return" I will return a string formatted String "My name is " I want to insert the dog’s name here %s, is basically a placeholder and s it’s for string, it means a string will be used here " The name of my owner is " %s After we put the variables, "name and "owner" After we go to the "human" class and create a private property So, private String name and builder Then we go to the "Main" class, here what we want, is to create a human with his name. So, Human I’m going to call it Bob. new Human Always as the name "bob". Right now, let’s create a dog with his name. Dog name "tom" new Dog As you can see with the error here, is that we need a chain that is the name and we need a "human" instance So I’m going to call my dog tom and I’m going to pass the bob instance here Now what I’m going to do next is call the "toString" method of our dog class, it’s going to be tom. So when I do that. It’s gonna flip that chain back on us and we’ll launch our program. As you can see here we have tom but on the other hand we do not have bob how to solve this problem. remember that this refers to a representation in the form of a chain, so all we have to do is to move towards our "Human" class. The toString method So, public String toString Return "name" Then, we relaunch our program. As we can see. We have "tom" and bob And that’s basically what a composition means in Java, it’s a way for you to reference an object that doesn’t belong to your class. That’s it for this video. I’ll see you next time!