Classes | Primitive types |
---|---|
Uniform reference model, like ML and Smalltalk | Pass by value/copy |
Can subclass, define methods, etc. (normal "object-oriented" stuff) | Cannot |
Can pass references to methods that expect Object parameters. | Cannot |
A: Java provides a wrapper class for each primitive type, in the java.lang package. Therefore, if you want to treat an int as an object, you can "wrap" it in an instance of the class java.lang.Integer; for char, you can use class java.lang.Character, etc.:
char c = 'h'; Character objectC = new Character(c); char d = objectC.charValue();
Note that primitive types can be modified directly, but instances of the wrapper classes are immutable---they do not have any methods that change their value.
Meta-note: immutable objects in OO languages provide many of the same benefits that immutable values in functional languages do. You can pass and share them freely without worrying about side effects. So, standard string objects (java.lang.String), for example, are immutable. (java.lang.StringBuffer is the mutable string class)
By the way, strings are objects that have special syntactic support. For example, string literals are actually instances of class String:
String s = "hi"; // These two lines produce equivalent-valued String t = new String("hi"); // String objects. if("hi".equals(t)) // BTW, by convention the message System.out.println("eq0"); // .equals() means value comparison. if(t == "hi") // Also BTW, == is "object identity" testing. System.out.println("eq1"); // t and "hi" have the same value, but else // are different objects, so the identity System.out.println("not1"); // test will return false.