使用子类引用与超类引用引用子类对象
在 Java 继承中,一些基本规则包括:
超类(父类)与子类(子类)之间存在对象关系,而子类与父类对象关系则不存在。这意味着父类引用可以持有子类对象,而子类引用不能持有父类对象。
在重写非静态方法的情况下,运行时对象将评估执行子类方法还是超类方法。而静态方法的执行取决于对象持有的引用类型。
继承的另一个基本规则与静态和非静态方法的重写有关,Java 中的静态方法不能被重写,而非静态方法可以。但是,子类可以定义与超类具有相同静态方法签名的静态方法,但这不被视为重写,而是被称为隐藏超类的静态方法。
基于上述规则,我们将通过程序观察不同的场景。
示例
class Parent { public void parentPrint() { System.out.println("parent print called"); } public static void staticMethod() { System.out.println("parent static method called"); } } public class SubclassReference extends Parent { public void parentPrint() { System.out.println("child print called"); } public static void staticMethod() { System.out.println("child static method called"); } public static void main(String[] args) { //SubclassReference invalid = new Parent();//Type mismatch: cannot convert from Parent to SubclassReference Parent obj = new SubclassReference(); obj.parentPrint(); //method of subclass would execute as subclass object at runtime. obj.staticMethod(); //method of superclass would execute as reference of superclass. Parent obj1 = new Parent(); obj1.parentPrint(); //method of superclass would execute as superclass object at runtime. obj1.staticMethod(); //method of superclass would execute as reference of superclass. SubclassReference obj3 = new SubclassReference(); obj3.parentPrint(); //method of subclass would execute as subclass object at runtime. obj3.staticMethod(); //method of subclass would execute as reference of subclass. } }
输出
child print called parent static method called parent print called parent static method called child print called child static method called
因此,使用超类引用和使用子类引用进行引用的区别在于,使用超类引用可以持有子类对象,并且只能访问子类中定义/重写的方法,而使用子类引用不能持有超类对象,并且可以访问超类和子类的方法。
广告