S. A. Malik
S. A. Malik

Reputation: 3655

Confusing Java Class concept

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.

Upvotes: 2

Views: 297

Answers (4)

NPE
NPE

Reputation: 500167

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.

Upvotes: 12

Bhaskar
Bhaskar

Reputation: 7523

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.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59987

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.

Upvotes: 1

Petar Ivanov
Petar Ivanov

Reputation: 93000

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++.

Upvotes: 1

Related Questions