javainner-classescomposition

Composition vs Inner Classes


What are the differences and the similarities between composition and inner classes? I am trying to learn the principles of Java and try to figure out the whole image. For me is better to make analogies and to see the differences and similarities between concepts, in order to use them corectly.

Definition of composition: "Composition is the design technique to implement has-a relationship in classes". "Java composition is achieved by using instance variables that refers to other objects"

Definition of inner class(or member class,not anonymous): "A member class is also defined as a member of an enclosing class, but is not declared with the static modifier. This type of inner class is analogous to an instance method or field. An instance of a member class is always associated with an instance of the enclosing class, and the code of a member class has access to all the fields and methods"

So, by confronting the two definitions, i see some similarities:

1. Both have HAS-A relationship
2. Both are strictly dependent on the outer class lifetime
3. can be declared private

Differences:

1. Inner classes uses classes, composition use instances (?!)
2. In composition no restriction to use the variables of the "outer" class

Please correct me if I am totally wrong, I need to trace better the limits of two concepts.


Solution

  • These two concpets are related. To better organize my thoughs let's define A and B:

    Example:

    class Driver {
    }
    
    class Car {
    
        // A
        class Engine {
            void start() {
                if (gasLevel > 0) {
                    ...
                }
            }
        }
    
        //B
        Driver driver;
    
        int gasLevel;
    
    }
    

    That said:

    To sum up, composition between two distinct classes and composition with an inner class are ways to control the level of coupling and cohesion of your system.