我有一个父类(super class)人员和一个子类学生。我创建了一个 person 类型的学生对象,并想调用 person 类型中不存在的学生特定方法。我有下面两种方法可以做到这一点,我很想知道一种方法优于另一种方法,或者它们都达到相同的结果吗?
Person newStudent = new Student("Scott", 22, "B22334952");
//method1: make a reference of newStudent and cast to Student
Student studentRef = (Student) newStudent;
System.out.println(studentRef.getUserId());
//method2: cast newStudent, but don't create a reference
System.out.println(((Student) student2).getUserId());
最佳答案
他们都会有相同的结果。
如果需要重用转换引用,请创建一个变量来存储转换结果。
当您执行类型转换时,您正在为自己做好准备ClassCastException
,所以要时刻保持警惕。在尝试强制转换之前,您始终可以检查类型
if (newStudent instanceof Student) {
Student studentRef = (Student) newStudent;
}
关于java - 在 Java 中是否有首选的对象转换方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552613/