//: UaryPlus.java
/*
*1.Unary Plus "its only effect is to promote byte,short,or char to int"
*Thinking in Java P101
*
*2.当比int小的基本类型运算时也会自动转换为int
*/
/*
*3.wrapper primitives:wrappper type(wrapper class)是一种类,可以调用方法
*/
class UaryPlus
{
public static void main(String[] args)
{
byte a1 = 1;
//!primitive无法调用方法(方法只能由对象使用)
//!System.out.println(a1.getClass().getName());
System.out.println(getType(a1)); //java.long.Byte
Byte a2 = new Byte("1");
//Byte a2 = 1;
System.out.println(a2.getClass().getName()); //java.long.Byte
System.out.println(getType(-a2)); //java.long.Integer
System.out.println(getType(+a2)); //java.long.Integer
Character c = new Character('a');
System.out.println(c.getClass().getName()); //java.long.Character
System.out.println(a2 + c); //98
System.out.println(getType(a2 + c)); //java.long.Integer
}
public static String getType(Object o)
{
return o.getClass().getName();
}
}
//“.getClass().getName()”亦可为“.getClass().toString()"
//:~
主要是wrappper class的用法、出现原因。Java中基本类型并非是对象,这使得”Everyting is an Object”并不精确。为了保持一致性、利用类的益处所以提供了对基本类型的封装类(即wrapper class)。当两者初始化时也会有一些差异:
//: WrapperPrimitives.java
class WrapperPrimitives
{
public static void main(String[] args)
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
System.out.println(c1.i);
System.out.println(c2.i);
}
}
class Class1
{
int i;
}
class Class2
{
Integer i;
}
/*Output:
*0
*null
*///:~
参考:1.Stack Overflow: When to use wrapper class and primitive type