Java 类型系统与访问控制深入解析
1. 类型兼容性与转换
Java 是强类型语言,在编译时会检查类型兼容性,防止不兼容的赋值。下面详细介绍类型兼容性和转换的相关内容。
1.1 兼容性
- 赋值规则 :当把表达式的值赋给变量时,表达式的类型必须与变量的类型兼容。对于引用类型,表达式的类型必须与变量声明的类型相同,或是其亚型,或者能转换为该类型。例如:
class Attr {}
class ColorAttr extends Attr {}
public class CompatibilityExample {
public static void acceptAttr(Attr attr) {
// 可以接受 ColorAttr 类型的对象
}
public static void main(String[] args) {
ColorAttr colorAttr = new ColorAttr();
acceptAttr(colorAttr); // 合法,因为 ColorAttr 是 Attr 的子类
// 下面的赋值不合法
// Attr attr = new Attr();
// ColorAttr colorAttr2 = attr;
}
}
- null 的兼容性 :null 对象引用与所有引用类型兼容,
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



