[英]In Java is there a preferred method of casting an object?
I have a superclass person with a subclass student. 我有一个超人,一个小学生。 I have made a student object of type person, and wanted to call a student specific method which does not exist in the person type. 我已经创建了一个类型为person的学生对象,并想调用该学生类型中不存在的特定于学生的方法。 I have two methods below that can do this, and I was curious to know is one method superior to the other, or do they both achieve the same outcome? 我下面有两种方法可以做到这一点,但我很想知道一种方法优于另一种方法,还是两者都能达到相同的结果?
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());
They'll both have the same outcome. 他们都会有相同的结果。
Create a variable to store the result of the cast if you need to reuse the cast reference. 如果需要重用转换引用,请创建一个变量以存储转换结果。
When you perform a cast, you are setting yourself up for ClassCastException
, so always be mindful. 执行强制转换时,您将自己设置为ClassCastException
,因此请务必注意。 You can always check the type before you attempt a cast 尝试投射之前,您始终可以检查类型
if (newStudent instanceof Student) {
Student studentRef = (Student) newStudent;
}
Both are similar. 两者是相似的。
Use the second one if you don't want to use that information anymore. 如果您不想再使用该信息,请使用第二个。
Use whichever you prefer, this is a meaningless micro-optimization and will result in equivalent byte code. 使用任何您喜欢的方法,这都是毫无意义的微优化,将导致等效的字节码。 You could also use Class.cast(Object)
like 您也可以使用Class.cast(Object)
System.out.println(Student.class.cast(newStudent).getUserId());
Best of all, don't cast . 最棒的是, 不要投 。 Casting means your code is making assumptions that cannot be verified at compile time, and that's a recipe for trouble. 强制转换意味着您的代码所做出的假设无法在编译时进行验证,这是麻烦的秘诀。 Declare variable types that capture the full requirements and expectations of their values, and rely only on those declared types. 声明变量类型,这些变量类型捕获其值的全部要求和期望,并且仅依赖于那些声明的类型。
So, 所以,
// Declare a Student because a plain Person won't do
Student newStudent = new Student("Scott", 22, "B22334952");
System.out.println(newStudent.getUserId());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.