4) Java Objects Lesson

What is Object Composition?

4 min to complete · By Ryan Desmond

Object composition in Java is when the instance variables of an object reference another object.

How Does Composition Work?

You can think of composition as one object having a "Has a" reference to another object. Since composition implies one object having its instance variables referencing another object, this means that the object depends on the other object. objectA "has a " variable pointing to objectB.

Java Composition Example

In the example below, you'll see how a Car "Has A" Engine and "Has A" Stereo. This Car object is composed of two String objects, one Engine object, and one Stereo object.

class Main {
  public static void main(String[] args){
      Engine myEngine = new Engine(400);
      Stereo myStereo = new Stereo("Panasonic");

      Car myCar = new Car(myEngine, myStereo, "Ford", "Black");
      
      System.out.println("I drive a " + myCar.color 
           + " " + myCar.model + " with a sweet "
           + myCar.stereo.brand + " stereo, and a " 
           + myCar.engine.horsePower 
           + " horse power engine");
  }
}

class Engine {
 double horsePower;

 public Engine(double horsePower){
     this.horsePower = horsePower;
 }
}

class Stereo {
  String brand;
  
  public Stereo(String brand){
      this.brand = brand;
  }
}

class Car {
  Engine engine;
  Stereo stereo;
  String model;
  String color;

  public Car(Engine engine, Stereo stereo, String model, String color){
      this.engine = engine;
      this.stereo = stereo;
      this.model = model;
      this.color = color;
  }
}

Composition (and Aggregation which is basically the same concept), as well as inheritance (which you'll discuss shortly), are widely used to model the world around us. When you think about it, you can create any Java objects you want, and they can be composed of any Java objects you need. This gives us a huge amount of flexibility and potential to create very powerful applications that model the world very specifically.

Experiment with Object Composition

In the code editor below, create at least three new, simple classes. Demonstrate object composition with these classes. Declare and instantiate an object in the main() method that is a composite object.

class Main{
   public static void main(String[] args){
      // create a composite object here 
      // after creating your new classes below
      // refer to the previous example for guidance


   }
}

// create your first class below this line

// create your second class below this line

// create your third class below this line

Summary: What is Java Composition

  • Object Composition is the process of relating one object with another
  • With composition, at least one object depends on another object
  • Aggregation is almost the same concept as composition
Morty Proxy This is a proxified and sanitized view of the page, visit original site.