在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
因此,使用超类引用进行引用和使用子类引用进行引用之间的区别在于,使用超类引用可以保留子类的对象,并且只能访问由子类定义/覆盖的方法,而使用子类引用不能保留超类的对象,并且可以访问超类和子类。