r/learnjava • u/ajihkrish • May 28 '24
How in Java it is feasible?
Hi
How in Java below is feasible?
Object array = new Long[10]; // ValidBut not,
Long array = new Long[10]; // Not validWhat 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
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
4
u/josephblade May 28 '24
Object longArrayAsObject = new Long[3];here you create an array and then put it in a container that says "this is an object'. this is correct, right since an Array (of longs) is an Object
Object longAsObject = new Long(33);here, we create a single Long object and then put it in a container that says "this is an object". this too is correct since a Long is an Object.
Long longArrayAsLong = new Long[3];here we create an array and then try to store it in a container that says "this is a Long". since an Array is not a Long (it is an array) this is not correct.
a variable type is a description of what object sits inside of it. A variable of type Object can hold any object (Long, Long[], String, etc). A variable of type Long can only hold Longs (and if it was possible, any subclasses of Long, but nothing else)
one last explanation that may help: when you give a variable a type it declares to the programming universe: this variable can be used in this way. It's memory layout follows this pattern. the compiler will then safeguard you against making mistakes and will only allow objects that follow that layout / provide the method calls that that type provides.
for instance:
public class A { int one; int two; byte three; byte four; }an object of type A would look like this in memory:
[4 bytes][4 bytes][byte][byte]now imagine I do this:
public class B { int other; }with B looking like:
[4 bytes]and we call the following code:
A a = new B();if I try to access B as an A and the compiler doesn't stop me, then when I do: a.one it might be kind of ok since the first 4 bytes in both cases are the same. but if you did a.two what would happen? you might access memory that's not in use. or worse, memory in use by another object.
And what would happen if you call a method that the other object doesn't support.
so for this reason you cannot assign one type of variable to another unless they literally are that type. this is also part of what makes subclasses work. subclasses wrap like onion layers around previous layers.
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.
14
u/ShadowRL7666 May 28 '24
Arrays in Java are objects, and they can be assigned to variables of type Object. However, assigning an array directly to a non-array type (like Long) is not allowed because they are fundamentally different types.
4
3
u/plastikbenny May 28 '24 edited May 28 '24
Object is the root of the class hierarchy including arrays. It's where they all get toString() equals() etc from. So Long[] inherits Object.
However an array of Long (Long[]) does not inherit a Long.
3
u/nekokattt May 28 '24
A long is not an array of longs, in the same way a string is not an array of strings
An array of longs is an objects, because all arrays are objects in Java. That is just how it works.
System.out.println(new Long[3] instanceof Object);
// true
System.out.println(new Long[3] instanceof Long);
// false2
u/Immediate_Narwhal_54 May 28 '24
It's easy.
All arrays are objects, but arrays of longs are not a long.
2
u/Pedantic_Phoenix May 28 '24
It's weird to ask this on reddit when you can google it in 10 seconds. But maybe it's just me
1
u/raxel42 May 28 '24
Object is the most common type.
Object can hold everything (even primitives after autoboxing)
1
u/vegan_antitheist May 28 '24
Java arrays are not type safe. See this detector for spotbugs: https://spotbugs.readthedocs.io/en/stable/detectors.html#covariantarrayassignment
•
u/AutoModerator May 28 '24
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full - best also formatted as code block
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.