r/learnjava • • May 28 '24

How in Java it is feasible?

Hi

How in Java below is feasible?

Object array = new Long[10]; // Valid

But not,

Long array = new Long[10]; // Not valid

What is going on here, Technically?

My doubt is, how Object Type holds array value, what’s going on here?

Thanks in advance

Edit : It is not specific to Long Type but we can also provide other Types, have given Long Type for example purpose

1 Upvotes

15 comments sorted by

View all comments

2

u/Mortomes May 28 '24

Every class in java (including arrays) implicity inherits the Object class. Since a Long[] inherits from Object, it can be assigned to an Object.

A Long and a Long[] are not the same class, nor do they inherit from each other, so a Long[] can not be assigned to a Long.

1

u/ajihkrish May 28 '24

Understood

But you say Long[] inherits from Object, and Long also inherits Object, right, then Long should hold values?(I know it is not valid, but wanting explanations)

Thanks

1

u/J-Son77 May 28 '24

What you trying to say is: a cat is an animal, so a dog must be a cat too because a dog is also an anmimal.

Everything (expect primitives) is an Object in Java. You can walk the inheritance tree upwards. This works:

Object obj = new Long(2);
Number num = new Long(2);
Long lng = new Long(2);

Because Long inherits from Number inherits from Object.

But you can't write

String str = new Long(2);

Because String is not in the inheritance tree path of Long. String is not a Long.

And Long[] is not the same as Long. Long is an object wrapper for primitive long. Long[] is an array, a bucket to hold Long-Objects. Long holds exactly one long value. new Long[3] is a bucket which can hold a maximum of 3 Long-Objects each holding exactly one long value.

3

u/Mortomes May 28 '24

And to refer back to your original analogy, saying a Long is the same as a Long[] is like saying a litter of puppies is the same as a puppy.