Answer the question
In order to leave comments, you need to log in
Why can Object be assigned a primitive value?
I always thought that reference types and primitive types could not be connected in any way, but I came across this absurdity:
public MagicClass{
Object val = 12345; //да-да, вам не показалось, мы присваиваем ссылочному типу примитив!
public void print(){ System.out.println(val); }
}
12345
Process finished with exit code 0
int
(And not only of type , but also of type double
, etc.)?
Answer the question
In order to leave comments, you need to log in
During the execution of the construction Object val = 12345
, a primitive value of the int type is auto -boxed into an object of the Integer type and its reference is assigned to the val variable. The latter is possible because Integer inherits from Object.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question