《从C/C++到Java入门指南》- 22.对象的转型

发布于:2024-09-05 ⋅ 阅读:(16) ⋅ 点赞:(0)

对象的转型

向上转型

将子类型对象转换成父类型,称之为向上转型。

class People {}
class Teacher extends People {}


public class Main {
   
	 public static void main(String args[]) {
		 People teacher = new Teacher();
		 System.out.println("0");
	 }
}

这里将子类(Teacher)转换成了一个父类(People),将一个具体类转换成了一个抽象类。需要说明的是,向上转型是安全的。也就是说父类可以引用子类。

class People {
	int c = 4;
}
class Teacher extends People {
	public int a = 3;
}


public class Main {
	 public static void main(String args[]) {
		 People teacher = new Teacher();
//		 teacher.a = 3;	// 编译报错
		 teacher.c = 7;
		 System.out.println(teacher.c);
	 }
}

可以看出,转成父类后,只能调用父类拥有的方法和变量。

向下转型

向下转型是不安全的,举个例子,人不一定是老师,老师一定是人。如果将随便一个人随便任命为老师,很可能会出错。

class People {
}
class Teacher extends People {
}


public class Main {
	 public static void main(String args[]) {
		 Teacher tom = new People();
		 
	 }
}

显而易见的得到一个报错提示。但其实可以使用强制转型来向下转型,相当于告诉编译器:这个人就是个老师!

class Father {
}
class Child extends Father {
}


public class Main {
	 public static void main(String args[]) {
		 var father = new Father();
		 Child chlid = (Child) father;
	 }
}

编译器不会有错误提示,但是运行后会得到报错。

Exception in thread "main" java.lang.ClassCastException: class Father cannot be cast to class Child (Father and Child are in unnamed module of loader 'app')
	at Main.main(Main.java:10)

注意:没有继承关系的对象之间不可以进行转型操作。


网站公告

今日签到

点亮在社区的每一天
去签到