:::info
Java 有5种 Type : class 、 interface 、 array class 、 primitive type 、 type varibales 。他们又可以归为两类: primitive types 和 reference types .
:::
每个实例数据都属于上面五种类型中一种, Type 定义了它的结构,所占的内存,在内存中布局,更重要的是,决定了如何和这个类型数据交互。
什么是 primitive types ?
一个 primitive type 总是持有一个同类型的原生值。这个值的改变只能通过对这个变量的赋值操作。
比如 int a = 1; 只能通过 a = 2; 这种直接赋值来改变 a 变量的值。
a) 整数类型有
byte、short、int、long, 这些是 8-bit、16-bit、32-bit、64-bit的有符号整数,相应的,还有char,他是 16-bit 无符号整数。 b) 浮点数类型float,他的值是 32-bit IEEE 754浮点数,还有double,他的值是 64-bit IEEE754浮点数。 c)boolean型type只有两个值:true、false。
什么是 reference types ?
一个 reference type 总是持有 指向一个对象的引用 的值。和 primitive types 的区别是,
直接赋值,如 ClassA a = new ClassA(); a = b; 改变的是引用变量 a 本身,而非 a 所指向的对象,
要改变 a 指向的对象要通过 a.method(args) 。这也就是上面提及的 type 决定了你和它交互的方式。
除去
primitive type,其余4种都是reference types:class types、interface types、array types、type variables。
下面一一介绍四种 types 。
在 JLS 中, Class 定义如下:
一个类声明指定了一个新命名的引用类型。 有两种类声明:常规类声明、枚举类声明。
ClassDeclaration:NormalClassDeclarationEnumDeclarationNormalClassDeclaration:{ClassModifier} class TypeIdentifier [TypeParameters] [Superclass] [Superinterfaces] ClassBody
注意上面有个 [TypeParameters] , 这表明 class types 也包含那些泛型类。
:::warning
笔者在有些文章上看到把 泛型 列到了 Java 五大类型里面,这是不对的。
:::
class Example<T>{}
这个 class types 被叫做 Example 。
简单的说,一个 class type 包括了枚举、我们的常规类(非泛型)像 String 等等,还有泛型类。
类似的, infterface type 和 array types 也很清晰。 int[] 、 String[] 等等都是 array types 。
最后来看看 type variables 。
type variables是一个非限定标识符,在类、接口、方法、构造函数中可以作为任何一种type使用。 也即可以引用五种type。
public static <T> void sis(T a) {}public <T, M> void pick(M m) {Short[] sa = {1};T ff = (T)m; // ✅只是编译过,运行时未知sis(m); // ✅sis(1); //✅sis(sa); //✅}
上面的 M 、 T 就是 type variables 。通过指定上届,还可以调用方法。
class Test {public <T extends C & I> void test(T t) {t.mI(); // OKt.mCPublic(); // OKt.mCProtected(); // OKt.mCPackage(); // OK}}
