Composition vs Inner Classes
Asked Answered
H

3

12

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.

Hartung answered 1/11, 2016 at 13:21 Comment(5)
That's comparing apples to oranges. You have to have some common ground on which to compare two things. It's like comparing a washing machine with a train, on the basis that both have engines. You should read examples showing the use of these two concepts, and see if they can both be used to solve problems in the same domain or not.Selfmortification
Right. But on what grounds are you trying to compare them? For example, you can say: "To solve problem X, I can use this solution, or that solution, and the two solutions are similar in that they both solve problem X, and perhaps also in other aspects, but they are different in aspect A, B, and C". But you start from a common ground: the need to solve problem X.Selfmortification
@Selfmortification , could i quote you if i would have to answer such a question onn a jobs interview ? :)Hartung
You could, though I doubt that my nickname would impress anybody in a job interview... Remember, though, that job interview questions are not always there to test your knowledge, but to test the way you think about a problem. So perhaps they expect you to realize that there is no common ground and say so.Selfmortification
@RealSkeptic, if i find some similarities between concepts, for me is a common ground. Maybe you are talking about different purposes.And that is where i am weaker maybeHartung
F
8

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

  • A is a class member composed by an inner class.
  • B is a class member composed by an instance of an external class.

Example:

class Driver {
}

class Car {

    // A
    class Engine {
        void start() {
            if (gasLevel > 0) {
                ...
            }
        }
    }

    //B
    Driver driver;

    int gasLevel;

}

That said:

  • A is a field
  • B is a field
  • A is an inner class
  • B is not a inner class
  • A has access to Car internal state (gasLevel)
  • B don't have access to Car internal state (gasLevel)
  • Engine don't exists without an instance of Car.
  • Driver exists without an instance of Car.

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.

Frijol answered 1/11, 2016 at 18:25 Comment(5)
thanks for the fine explanation. But B shouldn t be an Association(or Aggregation) in your case? Composition: A consists of B; B is a part of A and hence cannot exist without A (A owns B); in your case Driver exists without an instance of car. For me is just a form of Association(or maybe better Agreggation): Association: A uses B, A is related to B in a given wayHartung
I agree that my response was not strictly precise with the term composition. However, your initial definition of composition isn't precise too. To be precise we need to call B an aggregation. Both composition and aggregation are associations.Frijol
We can call A a composition and B an aggregation.Frijol
Hey, how would you approach a situation when driver needs to know gasLevel? Would it be OK practice to put a Car reference inside Driver class?Epithet
Yes, and also adding a setter on Car to expose gasLevel value. Note that this example is not about best practices on object modeling.Frijol
S
1

You're right that composition and inner-classes both implement "has-a" schemes, but they have a lot of differences.

Composition is when your class has an instance of another class as an instance variable (sometimes called a field).

public class A {
    B otherObject;
    /* Other fields and methods go here */
}

otherObject in this case is just a reference to an instance of another object of type B. otherObject can exist independently of your instance of A, and multiple instances of A can have references to the same B.

An inner class is when the class definition is actually contained within the outer class.

public class C {
    class D {
        /* Inner class stuff goes here */
    }
}

This is used mostly for logical grouping. In this scenario, D is directly associated with C, whereas B may or may not be a logical child of A. Access to D outside of C becomes a little more complicated, but it can only be accessed through an existing instance of C.

So, by confronting the two definitions, i see some similarities: ... 3. can be declared private

You're right that both can be declared as private, but the meaning of private for these two is very different. private as used in composition means that access to that reference is restricted to that class. Say that in your execution code, you have an objectA of type A. You could NOT attempt to access objectA.otherObject. otherObject can only be referenced from the body of A. When you declare an inner class as private, it means that use of that entire class is restricted to the body of A. You couldn't use it anywhere in any other class.

Sokul answered 1/11, 2016 at 17:32 Comment(1)
You have confused composition with aggregation in this explanation. When object of one class O1 is associated with object of another class O2 such that the O1 and O2 can exist independently of each other, that constitutes aggregation. Usually this is done by providing the instances to the references via constructors/setters. Rather than defining them manually in the class itself. Correct me if I am wrong.Incommunicado
E
0
  1. In composition no restriction to use the variables of the "outer" class

In composition you cannot access enclosing class private fields directly. An inner class has access to outer class fields by default.

Ethology answered 18/9, 2023 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.