In C++, you CAN do this:
class A {
A *a;
}
This is how you would implement many data structures, including linked lists.
As you mentioned, you CAN'T do this in C++:
class A {
A a;
}
You can't do that in C++ for a couple reasons: Not only because it doesn't know the memory size of A
(as you mentioned), but also because it would mean that every A
would have a member of type A
which would recurse on forever.
So, Java, allows the equivalent of the first example above:
class A {
A a;
}
It just so happens that this syntax looks the same as the second example of C++ syntax, but in fact, it has the same meaning as the first C++ example: Class A
has a member variable of type "pointer" (C++) or "reference" (Java) to an object of class A
.
The second C++ syntax has no equivalent Java syntax, because in Java, all instances of a class (i.e. non-primitives) are always references.