Showing posts with label composition versus aggregation. Show all posts
Showing posts with label composition versus aggregation. Show all posts

Wednesday, March 19

Composition versus aggregation Java Code example



Aggregation


Read comments in Test class to understand the scenario / Code flow


package com.sam;

 class Car {
    Engine engine;

    public Car() {

        engine = Engine.getEngineInstance();

    }

    Engine getEngine() {
        return this.engine;
    }

}

class Engine {

    private Engine() {

    }

    public static Engine getEngineInstance() {

        return new Engine();
    }

    public void performAction(String str ) {

        System.out.println("Performed.."+str);
    }
}

public class Test {

    public static void main(String args[]) {

        Engine engine = Engine.getEngineInstance(); // can ncreate Engine instance ,
        // Engine can exist on its own ,
        // It can exist even without car instance
       
        engine.performAction("With Out Car Instance");

        Car car = new Car(); // Car class has dependency on ENgine class to perform Action
                             // But Engine Class instance can be created and used even without
                             // creating Car class instance

        car.getEngine().performAction("With Car Instance");

    }
}








composition


Read comments in Test class to understand the scenario / Code flow


package com.sam;
class Car {
    Engine engine;

    public Car() {

        engine = new Engine();

    }

    Engine getEngine() {
        return this.engine;
    }

    class Engine {

        private Engine() {

        }

        public Engine getEngineInstance() {

            return new Engine();
        }

        public void performAction(String str) {

            System.out.println("Performed.." + str);
        }
    }

}

public class Test {

    public static void main(String args[]) {

        Engine engine = Engine.getEngineInstance(); // compilation error / can not create Engine instance ,
        // Engine can not exist on its own ,
        // It can exist only with car instance

        engine.performAction("With Out Car Instance");

        Car car = new Car(); // Car class has dependency on ENgine class to perform Action
                             // SO Engine Class instance can be created only with
                             //  Car class instance

        car.getEngine().performAction("With Car Instance");

    }
}