Just trying to understand the behavior of java.lang.Object class.
public class TypeCheck{
static void printMethod(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
Object obj = new Object();
Integer intObj = new Integer(12);
String stringObj = new String("Hello");
printMethod(obj); //---> java.lang.Object@78b5f53a
printMethod(intObj); //---> 12
printMethod(stringObj); // ---> Hello
}
}
My questions are:
- When should we use Object class?
- But, when I only pass
printMethod(intObj)and inprintMethod(Object obj)I do an addition:System.out.println(obj+1)it does not work. Ifobjrecognizes that it’s an Integer, why can’t I do operations on it?
Exception:TypeCheck.java:5: operator + cannot be applied to java.lang.Object,int System.out.println(obj+1); -
Now, if I do this:
public class TypeCheck { static void printMethod(Object obj) { System.out.println(obj.getClass().getName()); } public static void main(String[] args) { int i = 666; printMethod(i); } }It returns
java.lang.Integer, but it’s defined asint(primitive type). Why does Java convert a primitive type to it’s wrapper class when passed to anObject.
That should work.See belowint, are not objects. Therefore it needs to be made an object (boxed) to be passed as one.EDIT in response to question edit:
(Number 2)
Inside of
printMethod, the type ofobjis notint, it isObject. You can’t add objects! You would need to cast it back toIntegerorintbefore you could perform such operations on it. What would the+do if you passed an instance ofTypeCheckintoTypeCheck.printMethod?