0

The following is an example of "composition":

public class Car
{
    Engine engine;  // Engine is a class
}

But is it still called "composition" if we are using primitive data types? for example:

public class Car
{
    int x;  // int is a primitive data type
}
user247763
  • 191
  • 5
  • 15

2 Answers2

-1

Composition is a relation defined between classes (reference types), and not primitive types.

Cosmin Ioniță
  • 3,598
  • 4
  • 23
  • 48
  • What about .NET where even Java-primitive-like `struct`s all extend `System.Object`, a .NET-twin of `java.lang.Object`? – terrorrussia-keeps-killing Jan 10 '21 at 16:29
  • I also asked my question at https://softwareengineering.stackexchange.com, this is the link to the question: https://softwareengineering.stackexchange.com/questions/420866/is-it-called-composition-if-we-are-using-primitive-data-types, and the answers over there say that it is still called “composition” if we are using primitive data types. So who is wrong, you or them?! – user247763 Jan 11 '21 at 15:32
  • The answer there is pretty clear. [Object composition](https://en.wikipedia.org/wiki/Object_composition) and [composite aggregation](https://en.wikipedia.org/wiki/Composition_over_inheritance) are 2 different things. In `object composition` you can have primitive types, but usually in OOP context, `composition` relates strictly to reference types (objects). – Cosmin Ioniță Jan 11 '21 at 15:38
-1

The reason the concept of composition exists is to differentiate it from inheritance. Whether one should use inheritance or composition is a question of good design and further explained here.

Since it's impossible to inherit from primitive types in Java, I'd say that the concepts of inheritance and composition don't make a lot of sense.

TL;DR: No

dranjohn
  • 673
  • 7
  • 22
  • I also asked my question at https://softwareengineering.stackexchange.com, this is the link to the question: https://softwareengineering.stackexchange.com/questions/420866/is-it-called-composition-if-we-are-using-primitive-data-types, and the answers over there say that it is still called “composition” if we are using primitive data types. So who is wrong, you or them?! – user247763 Jan 11 '21 at 15:31
  • I shouldn't have written the TL;DR at the end. The point I was really trying to get across was given in a comment on your question on the SE stackexchange, namely: Why does it matter what it's called? You can't inherit from primitives, so the composition vs. inheritance debate is settled. – dranjohn Jan 11 '21 at 16:11