Java中对象向下转换的规则
在Java中,向下转换是将父类对象转换为子类对象的过程。我们需要显式地执行此转换。这与我们在基本类型转换中所做的非常相似。
在这篇文章中,我们将学习向下转换以及在Java中向下转换对象必须遵循的规则。
Java中的对象向下转换
前面我们讨论过向下转换与类型转换有些相似。然而,也存在一些差异。首先,我们只能对基本数据类型进行类型转换;其次,它是一个不可逆的操作,即在类型转换中我们直接操作值,如果我们更改一次值,我们就无法恢复它。另一方面,在向下转换过程中,原始对象不会改变,只有它的类型改变了。
向下转换的必要性
例如,假设有两个类,一个是超类,另一个是它的子类。在这里,子类包含一些其超类想要使用的特性。在这种情况下,向下转换就出现了,它允许我们访问子类对超类的成员变量和方法。
语法
nameOfSubclass nameOfSubclassObject = (nameOfSubclass) nameOfSuperclassObject;
虽然这个语法看起来很简单,但我们很多人在编写这个语法时可能会出错。此外,我们不能像在下一个例子中那样直接向下转换对象。如果我们这样做,编译器将抛出“ClassCastException”。
示例1
下面的例子说明了提供错误的向下转换语法可能导致的结果。为此,我们将定义两个类,并尝试使用错误的语法向下转换超类对象。
class Info1 {
// it is the super class
void mesg1() {
System.out.println("Tutorials Point");
}
}
class Info2 extends Info1 {
// inheriting super class
void mesg2() {
System.out.println("Simply Easy Learning");
}
}
public class Down {
public static void main(String[] args) {
Info2 info2 = (Info2) new Info1();
// Wrong syntax of downcasting
// calling both methods using sub class object
info2.mesg1();
info2.mesg2();
}
}
输出
Exception in thread "main" java.lang.ClassCastException: class Info1 cannot be cast to class Info2 (Info1 and Info2 are in unnamed module of loader 'app') at Down.main(Down.java:13)
示例2
下面的例子演示了如何正确地执行对象向下转换。为此,我们将创建两个类,然后定义一个引用子类的超类对象。最后,我们使用正确的向下转换语法。
class Info1 {
// it is the super class
void mesg1() {
System.out.println("Tutorials Point");
}
}
class Info2 extends Info1 {
// inheriting super class
void mesg2() {
System.out.println("Simply Easy Learning");
}
}
public class Down {
public static void main(String[] args) {
// object of super class refers to sub class
Info1 info1 = new Info2();
// performing downcasting
Info2 info2 = (Info2) info1;
// calling both methods using object of sub class
info2.mesg1();
info2.mesg2();
}
}
输出
Tutorials Point Simply Easy Learning
结论
还有一个名为向上转换的概念用于修改对象。在这个过程中,子类对象被转换为超类对象。它可以隐式地完成。向上转换和向下转换这两个概念一起被称为对象转换。在这篇文章中,我们通过例子讨论了对象向下转换。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP