Understanding Java Composition Part 1
Articles Blog

Understanding Java Composition Part 1

October 14, 2019

So in the previous set of videos
we had a discussion about and learned about inheritance. It’s time now to talk about composition. Composition is another component of
object orientated programming and is very useful in day to day programming,
but just as a refresher, I’m gonna start off and just go over inheritance very
briefly before we move into composition. Best way to do that would be in examples. So let’s create two quick classes. First ones going to be vehicle. And vehicle is going to be very simple,
it’s gonna have one field. Private String name and
it’s gonna have a constructor. Pretty simple, concept of the vehicle. Let’s also create another class,
call it Car. We’re going to stem from vehicle and
add a couple of fields. So the number of doors,
private int, engine capacity. set up a constructor and there we go. Very simple little example. So, the car stems from vehicle. It’s got a Isa relationship with vehicle. Isa meaning that a car is a vehicle, so
that’s the relationship between the two. So you can quite correctly
say the car is a vehicle and that’s essentially what inherency is. The composition deals with
something different, and that deals with a relationship. And the best way to do this is
to go through an example, so let’s look at the scenario of a computer. So a computer has a motherboard,
a case, and a monitor, three example
things that it’s got with it. So the motherboard, the case,
and the monitor And not computers in the same sense that a car is a vehicle
but a computer has a motherboard. A computer has a case and
a computer has a monitor. So that’s what composition is is
actually modelling parts if you will, parts of the greater whole. So this case,
we’re going to model the computer and we’re going to model the has
A relationships of the motherboard. The case and the monitor. So let’s start off by actually creating
those three classes- the motherboard, the case, and the monitor. So now we start with the motherboard. New, Java class, motherboard. We’re going to create some fields. String Model. Private string manufacturer. It’s manufacturer of the motherboard. Private_int the number of RAM
slots of motherboard’s got. And the number of card slots for
video cards and so on. And lastly just the name of the bios. Just some typical things that
you would find in a motherboard. So I’m going to create
our public instructor. Which will be just all the fields. We’re going to create getters for all of
our fields because we don’t need setters. What we’re going to do is
add one public method which we’re going to call a low program. I’m going to pass a parameter
which will be the program name And we’re just going to print out that the
program, the program name is now loading. So that’s our motherboard class. Pretty straightforward as you can see,
nothing particularly complicated there. So let’s now move on to our monitor class. Create another new class. Monitor is the name. It’s also got some fields. We’re going to start with
the private string for the model. Private string manufacturer. Private int size. That will be the size of the screen. And let’s go with another one which
is going to be the native resolution. we’re going to call that a resolution,
native resolution. Resolution is going to be a class. We’re going to create a constructor,
like so. And we’re going to fix up that
resolution class in a minute. We’re going to create that class And what we’re going to do here is we’re
going to create a public method. Draw pixel at. That’s going to have an X,
Y location, and let’s say a color. And we’ll just do our,
a simple message that says drawing pixel. At x, the xy position in color, color. A very simple method, and then we’ll
just create some guesses as well. Just to get us for this class. So next we need to create
the resolution class. And with the resolution class,
that’s going to be the native resolution. So, what is the width and height and
maximum width and height of a monitor. How many pixels wide and
how many pixels down so to speak. So, we can go for width and
height Let’s just keep it simple there. So that would be
the resolution instructors. And some getters. So that’s our resolution. So going back now to the monitor. Find that the arrow’s now gone away. So this is an early example, we’re
gonna talk more about this shortly, but this is composition. So the resolution class
is part of a monitor, so the monitor isn’t a resolution,
but it has a resolution. So this is what composition is so we’re saying the resolution
is a component of a monitor. A monitor has a resolution
which is the native resolution. More on that shortly. So next we need to create a class for
case. New class, case, and
we’re going to have model, private string. Manufacturer, private string power supply. And let’s also have
a dimension Dimensions. New class we’re gonna create. It’s gonna be the dimensions, the width, height and
depth of the actual case itself. This is the case that
contains all the components. Okay and so the constructor is going
to have to accept those parameters. Like so.
We’re going to create a function called press power button. And we’re going to have a simple print
line that says, power Button pressed. Like so, and we’ll just do our
[INAUDIBLE] as we normally do. Okay so making good progress now. So the last thing we [INAUDIBLE] implement
before we can start seeing how some of this works,
is of course the dimensions class. And that’s gonna have a width,
a height, and a depth. So let’s create that. We’ll say dimensions. Int width, height, depth. Create a constructor for the three of
them and lets create a getter as well. Oops. Like so. Sometimes I have to mention so now if
i go back to case the hour goes away. So the case has got a model,
a manufacturer and a power supply. A case has got dimensions. The dimensions which are to the width,
the height and the depth. That is what our dimensions use. So of course the case has
got all these things. It has got a model. Has got a manufacturer,
has got a power supply, and of course, it does have dimensions. And that’s what we’re doing here again,
with our composition, we’re actually creating something, in this case,
another object that is part of the case. So, now we get to the fun part,
where we actually create a class that is comprised of the case,
the monitor, and the mother board. So, let’s create yet another new class. We’re gonna call that PC. This’ll be our personal computer. And instead of using extends,
we’re going to type private Case theCase. I have to use the word theCase there,
by the way, because if I just type case,
as you know by now, case is actually a reserved keyword,
so we’ll actually get an error. So we need to put case. You can call it something else,
but that will do. I’ll call it the case and
a piece it has got a case. It has got a monitor. We’ll just call these monitors. And of course motherboard,
motherboard, motherboard. And we create a constructor
like we normally do. This time we’re creating a constructor
that’s gonna accept three objects. Three different objects. And let’s create getter as well. So this is composition again. So we’ve created a new class called pc. It has a case, so that’s the case variable,
which is the field that we’ve defined. It has a monitor, a field monitor and
a field cord monitor and, of course, it has a motherboard, which in this case,
is a field cord motherboard. And you can see the obvious
advantage here, because if you’re using the extends
option to inherit, you can only, in Java, inherit from one class at a time So
you can see that we run into difficulties are running to limitations quite quickly,
if we’re using standard Java inheritance like we used the last few videos where
we can only extend from one class. In this case what we said is, the PC
comprises of these three other classes only the case the monitor and
the motherboard. So the PC has, in this case is
going to have, the objects that we create a off this class We’ll
have an object Case monitor and motherboard in each
instance that we create. So let’s actually run some code now and
see how it would use this in reality. So what we want to do
first is create a Case. So you put Case theCase=new Case. So that actually needs the model number so
let’s start with 220b. Manufacturer, let’s use Dell,
for want of a better name. Power supply we’ll say 240. And lastly it wants the dimensions, so it actually wants to know
what the dimensions are. So we can just dimensions in there. And, of course, what we’ll need to
do is create a new dimensions class. So I could put. So the dimensions, let’s go with
a width of 20 A height of 20 and a depth of five that would be our case. Weird size case, but for
this example it’ll be fine. So that’s our definition for case now. Remembering that when we create the PC
which we’re going to be doing shortly, it needs to know what the case is. And think of that as
putting a PC together. A PC generally can’t be put
together without a case. So what we’re doing here
is creating the case. So next we need to create a monitor. Create the monitor. You can view monitor. And the parameters for
this one, it’s a model so we’ll call it the 27
inch beast manufacturer, let’s try it. Acer, size we’ll go 27 for 27 inch and
it also needs a native resolution. You want to create that, so we’ll need to create that class,
and let’s do that a different way. I want to show you another way
of creating a class on the fly. If you don’t need to create a variable. You’re not going to use it for
anything else. You only want to pass it to a method. If you just type new resolution(2540,
1440) which is the size of my monitor. So that’s created a class without using a
variable which we don’t need in this case. And I’ll just fix that typo. That’s monitor. So we’ve now got a Case and a monitor that ultimately are gonna
be used to create our PC. Of course we now need a motherboard,
so let’s create a motherboard. So motherboard. Motherboard=new motherboard. And we need a model. We do at 200, and let’s go with Asus. The number of RAM slots,
well there’s four RAM slots on this one. Number of card slots,
let’s just say there’s six. And bios, let’s say it’s version 2.44,
so there’s our motherboard. So now we’re at the stage
where we can create our PC. Let’s put our PC together. How do we do that? Well we type PC, the PC equals a new PC,
And of course it then needs the case. The case, the motor, and the motherboard. They’re the three parameters that
will collectively make up our PC. So we’ve now created The PC class by
passing those three other objects to it. Now of course you’ve seen in previous
videos with inheritance we were able to use a method name, that is part of the basic class,
the super class in other words. But how do we get access to it? For example, if I wanna draw something using
the monitor, how do I access this method? So of course we’ve got the method draw
pixel at but how do we access that? How do we access that from our PC, cuz of course the PC has got getters,
but it hasn’t got any access that. We’re not overriding a method or
anything like that. So how do we access it? Well, one way of using it,
we could type the PC. Dot get monitor dot draw pixel at. We could do it that we could do
draw pixel at 1500, 1200 in red. That’s one way of accessing it. So what that is is just using the getter
function from here, which is returning The monitor which is the class
that has already been initialized. The object which has been
created in this class, returning that to the calling process. And from their we’re then calling the
method draw pixel at which is from that object that’s stored within the PC
class itself in the PC object, the instance that we’ve actually created,
and that’s invoking that method for us. So likewise we could put the PC,
get mother board, dot load program. How would we load the program? Windows 1.0.
We’re doing the same thing there. We’re getting the class,
the object that’s being created. And we credit the piece in class so
we’re accessing it within the PC object, and we’re getting it to load,
to call the method load program which is in that object, which of course,
is in the PC object that we’ve created. But of course for our personal case the PC
dot get the case, .pressPowerButton. We could do the same thing there. So now we’re accessing
ultimately these functions that are in these base classes and
not the case, the motherboard, and the monitor, but
accessing them via the PC object. So this is what composition is. This is the difference that inheritance,
the PC object that we’ve created here. So what we did to call the PC object was
we created our case, our monitor, and our motherboard. And in reality when you’re putting
a computer together, that’s what you’d be doing, you’d go away and you’d actually
buy the case, you’d buy the monitor, and you’d buy the motherboard, you’re then
putting it together to build the PC. So, in this case, what we’re doing is
we’re passing these to the constructor, which essentially is
giving those items and putting them together, which forms our PC. So, the PC has a case, has a motherboard. It has a monitor. So this is the way when you’re thinking of
whether to use inheritance or composition. Think about what you’re trying to do here. In this case we’re trying
to build a computer. And we need to access the case,
the monitor, the motherboard. We know that these things. The computer has got a case. It has got a monitor. It has a motherboard. So therefore composition is
probably a great way to go. But of course a case by
itself isn’t a computer. A case isn’t,
a monitor isn’t a computer and of course the motherboard
isn’t a computer. They’re part of a computer, but
not actually the whole computer which is why we’re using composition
here instead of inheritance. So, I’m gonna end this video here, we’ll continue on talking about
composition in the next video.

Only registered users can comment.

  1. .Thank You .You just described a great example greatly
    but for suggestion, I think it might be better to make it simpler … I mean do not going too much on details would be better

  2. Great tutorial Tim, however, I wanted to know what your reason for using only "getters" as oppose to using both "getters and setters"?

  3. Brilliant tutorial that I have ever watched ! By the way, I got a question, which platform you are using for code, I don't think it is eclipse 🙂

  4. I have owned the full course… Very depth course..

    I have one problem. In Monitor class, in getter method

    public String getNativeResolution() {
    return nativeResolution;

    It is showing me an error – Incompatible types:
    Required: Java.lang.String
    Found: com.Composition.Resolution

    I am also using same IDE…. Please help

  5. Thank you so much for this video! Very nicely explained. However, I have one question: where you called the drawPixelAt() method like thePC.getMonitor().drawPixelAt(x,y,""), this does the same thing as theMonitor.drawPixelAt(x,y,""). Why is the previous way better? Is it simply so you only have to remember the name of the PC object?

  6. Lately i've been hearing Composition > Inheritance, but i've been having trouble understanding how to build structures so that they avoid inheritance. Can someone give an example of how the vehicle class could be set up as composition instead of inheritance.

  7. This is an excellent example of Aggregation, not of Composition! In Composition the PC is the owner of its parts (motherboard,case, monitor) to enforce life-long dependency , so the motherboard, case and monitor objects should never exist as stand alone objects outside of the PC object, since this would mean you still would have a reference to them, even if you would mark the PC object for deletion (by setting: thePC = null;)

  8. A few very interesting points made in this video and I like that the computer example is easy to visualize. Maybe next time use less time creating classes and more focus on the subject at hand (what is composition). This is my personal opinion though.

  9. There is something that I can't undestand. For instance if the PC object is composed by a Case object, I think that you should have a new Case() sentence inside the PC constructor. The way you implemented it, creating the Case object in the main and passing the reference to the set method, looks more like aggregation than composition to me.

  10. do you make sure this is Composition ? if it compostion why dont you try add line pc = null and see whether or not Case ,Monitor and Motherboard already delete ?

Leave a Reply

Your email address will not be published. Required fields are marked *