:::info Java 有5种 Type : classinterfacearray classprimitive typetype varibales 。他们又可以归为两类: primitive typesreference types . :::

每个实例数据都属于上面五种类型中一种, Type 定义了它的结构,所占的内存,在内存中布局,更重要的是,决定了如何和这个类型数据交互。

什么是 primitive types ?

一个 primitive type 总是持有一个同类型的原生值。这个值的改变只能通过对这个变量的赋值操作。
比如 int a = 1; 只能通过 a = 2; 这种直接赋值来改变 a 变量的值。

a) 整数类型有 byteshortintlong , 这些是 8-bit、16-bit、32-bit、64-bit的有符号整数,相应的,还有 char ,他是 16-bit 无符号整数。 b) 浮点数类型 float ,他的值是 32-bit IEEE 754浮点数,还有 double ,他的值是 64-bit IEEE754浮点数。 c) booleantype 只有两个值: truefalse

什么是 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 typesinterface typesarray typestype variables

下面一一介绍四种 types

JLS 中, Class 定义如下:

一个类声明指定了一个新命名的引用类型。 有两种类声明:常规类声明、枚举类声明。

  1. ClassDeclaration:
  2. NormalClassDeclaration
  3. EnumDeclaration
  4. NormalClassDeclaration:
  5. {ClassModifier} class TypeIdentifier [TypeParameters] [Superclass] [Superinterfaces] ClassBody

注意上面有个 [TypeParameters] , 这表明 class types 也包含那些泛型类。

:::warning 笔者在有些文章上看到把 泛型 列到了 Java 五大类型里面,这是不对的。 :::

  1. class Example<T>{
  2. }

这个 class types 被叫做 Example

简单的说,一个 class type 包括了枚举、我们的常规类(非泛型)像 String 等等,还有泛型类。

类似的, infterface typearray types 也很清晰。 int[]String[] 等等都是 array types

最后来看看 type variables

type variables 是一个非限定标识符,在类、接口、方法、构造函数中可以作为任何一种 type 使用。 也即可以引用五种 type

  1. public static <T> void sis(T a) {
  2. }
  3. public <T, M> void pick(M m) {
  4. Short[] sa = {1};
  5. T ff = (T)m; // ✅只是编译过,运行时未知
  6. sis(m); // ✅
  7. sis(1); //✅
  8. sis(sa); //✅
  9. }

上面的 MT 就是 type variables 。通过指定上届,还可以调用方法。

  1. class Test {
  2. public <T extends C & I> void test(T t) {
  3. t.mI(); // OK
  4. t.mCPublic(); // OK
  5. t.mCProtected(); // OK
  6. t.mCPackage(); // OK
  7. }
  8. }