2

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.

3
  • 3
    I 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. Commented Sep 28, 2011 at 10:09
  • Obviously you're a little confused with C++ concepts too. Commented Sep 28, 2011 at 10:10
  • 1
    following error pops up in C++ error: field 'someName' has incomplete type compilation terminated due to -Wfatal-errors. Commented Sep 28, 2011 at 10:11

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1

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

C++ just has to be told it's a reference. See the other answers.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.