Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every data type inherit from Object?

Tags:

java

I have a method that takes a parameter of type Object:

  public static void test(Object foo) 
    {
    System.out.println(foo);
  }

I can pass foo: Strings, integers, booleans, etc...pretty much anything. I think this is possible because Object is the base class from which everything else inherits from, and therefore it accepts any data type as valid. I could understand this being the case with objects like Strings, and Arrays. But why is this the case with primitive types? Do integer, char, and boolean also inherit from Object?

like image 248
chopper draw lion4 Avatar asked Oct 28 '25 04:10

chopper draw lion4


2 Answers

No, primitive types do not inherit from Object since they're not classes. What happens when you pass a primitive type to this method from Java 5+ is called autoboxing, and the compiler will convert your primitive into one of the wrapper classes. For example, an int will be automatically converted into an Integer (using temporary variables behind the scenes) which will make the code compilable.

like image 178
Luiggi Mendoza Avatar answered Oct 29 '25 20:10

Luiggi Mendoza


in this boxing then widening occurs ....for eg: if long then it First box in to Long then widen to Object Class

like image 36
user3272090 Avatar answered Oct 29 '25 18:10

user3272090



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!