3

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?

Drunix
  • 3,313
  • 8
  • 28
  • 50
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100
  • @Chopper - see [Handling Duplicate Questions](http://blog.stackoverflow.com/2009/04/handling-duplicate-questions/) and signposts. Also, you should make the question in the title the same as the question in your body. The duplicate was for the question in your title. If you did not intend to ask the question in the title, then you should probably change it. – jww Oct 10 '14 at 04:21
  • @Chopper - since you accepted an answer, we have a better idea of what you wanted to know. Here's another that might be more constructive to you: [Does Java autobox when assigning an int to an Object?](http://stackoverflow.com/q/15139117/608639) – jww Oct 10 '14 at 04:53

2 Answers2

8

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.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

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

user3272090
  • 126
  • 5