Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing Java Class concept

Tags:

java

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.

like image 497
S. A. Malik Avatar asked Sep 11 '26 08:09

S. A. Malik


1 Answers

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.

like image 149
NPE Avatar answered Sep 13 '26 21:09

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!