New to java and a concept is confusing me a lot.
As a c++ programmer when we declare a class we can not have a property having an object of same class like lets say we have a class name Foo as belows
class Foo {
int age;
Foo someName;
}
the above code will give error. While in java i can do it. Is there a special reason behind it? And how does it happen. Any good read will be helpful.
-
3I am not a C++ expert but I'm pretty sure that you can have a class with a member of the same type in C++ too.Matteo– Matteo2011年09月28日 10:09:43 +00:00Commented Sep 28, 2011 at 10:09
-
Obviously you're a little confused with C++ concepts too.asgs– asgs2011年09月28日 10:10:36 +00:00Commented Sep 28, 2011 at 10:10
-
1following error pops up in C++ error: field 'someName' has incomplete type compilation terminated due to -Wfatal-errors.S. A. Malik– S. A. Malik2011年09月28日 10:11:09 +00:00Commented Sep 28, 2011 at 10:11
4 Answers 4
When you write Foo someName in Java, you're creating a reference to an object of type Foo. This is similar to writing Foo& someName in C++, which is allowed.
What is not allowed in C++ is for class Foo to have a member of type Foo (i.e. not Foo& or Foo*). If you think about it, this construct can't possibly make sense as it would require sizeof(Foo) to be infinitely large. This -- disallowed -- C++ construct has no direct Java equivalent.
Comments
In Java when you declare Foo someName, the someName is really a reference to an object of class Foo.
So there is no problem to have a property referencing an object of the same type.
This is similar to how you can have Foo& someName in C++.
Comments
Java stores objects as references. C++ doesn't. Therein is the difference.
With Java it does not need to know how much space to reserve for the Foo object. However in C++ the compiler needs to. So the C++ has an impossible task.
1 Comment
Thats because of an important between C++ and Java : in C++ , Foo above would be an object ; in Java Foo above is just a reference - not an object. ( You will have to write Foo someref = new Foo() for creating the object.