1.3.6 How to Define a Nested Field of the Same Type

We have already learned that classes are 'blueprints' that are composed of different 'things' such as fields and methods. When we define a class we can define fields that are of primitive and/or custom types. We can also define fields that are of the same class.

Let's say I wanted to instantiate a bowl of cereal. We don't really need to create a whole new class for this. Instead we can define fields of type Food in the Food class and use those to compose a larger object.


First, let's define fields in the Food class to represent the two parts of cereal: a milk and a grain.

There is nothing 'illegal' about this. The code will build just fine. So now, those two fields have the same members as the Food class.


So in the MainWidnow we can write this block of code:

A new Food object is being instantiated, then Food inside that same object is being instantiated. If we run the application we can see that the "Cereal" object has both a Milk and a Grain object that are both Food types.