Complex Classes UsageComplex Classes Usage

Using class objects in another class

Now we will discuss the more complex usage of classes, specifically using class objects within another class.

Team and players

Let's imagine a situation where we have a Team class. Every team should have players. We could fill the players field with simple String values representing their names, but that wouldn't be the best practice. It would be much better to create a Player class with its own fields and methods and then create an array of Player objects within the Team class. Let's consider an example:


As you can see, we are using an array of Player objects in the players field of the Team class. From this, we can draw a few conclusions:

  1. We can create arrays of objects from our own created class.
  2. We can use objects of one class within another class to improve the overall logic.

But the question arises: How do we fill this array?

Answer: To do this, we need to create several Player objects and add them to the array of players. Let's create a Dream Team in the main method and see an example:


We created 3 objects of the Player class and initialized their fields through the constructor. Then we create an array with the Player type and add Bob, Alice, and John to it. Next, we create a Team object and initialize its fields through the constructor. We initialize the players[] field with the previously created array. We print the object to the console and see that the Team object has Player objects in the output.

Owner and pet

Let's look at another simpler example. Let's say we have an Owner and a Pet. We will create a separate class for each. The Pet class will have only one field - String name. The Owner class will have two fields - String name and Pet pet.

Let's take a look at a code snippet where we implement this:


As you can see, these two classes are also connected, as the Owner class has a field of type Pet (which is the class we created ourselves!).

Everything was clear?

Section 5. Chapter 1