S
S
Sland Show2016-08-01 09:12:17
Java
Sland Show, 2016-08-01 09:12:17

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); }

}

And here's how the compiler reacts:
12345

Process finished with exit code 0

Essence of the question : Why can we assign a primitive value to Objectint (And not only of type , but also of type double, etc.)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-08-01
@SlandShow

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 question

Ask a Question

731 491 924 answers to any question