Java中如何通过子类对象调用父类的方法?
Java中通过子类对象调用父类被重写方法的实现方式
核心结论
Java支持调用父类的重写方法实现,但不能直接在外部代码中使用obj.super.getAge()这种语法——super关键字仅允许在子类的非静态方法内部使用,用来指代父类实例。针对你的场景,有两种可行方案:
方案1:在子类中新增方法调用父类实现
在子类Aman中添加一个专门的方法,内部通过super调用父类的getAge(),外部即可通过子类对象调用该方法获取父类的返回结果:
修改后的Aman类代码:
class Aman extends Human { public Aman(int age) { super(age); } public String getAge() { return new String("Aman's age is "+(this.age-1)); } // 新增方法,调用父类的getAge实现 public String getParentAge() { return super.getAge(); } }
在main方法中调用:
public static void main(String[] args) { Aman obj2 = new Aman(21); System.out.println(obj2.getParentAge()); // 输出Human's age is 21 }
方案2:使用反射机制在外部直接调用父类方法
如果无法修改子类代码,可以通过反射绕过动态绑定,直接调用父类Human中的getAge()方法:
修改后的main方法代码(需导入java.lang.reflect.Method):
import java.lang.reflect.Method; public class Main { public static void main(String[] args) { Human obj = new Aman(21); try { // 获取父类Human的getAge方法 Method humanGetAgeMethod = Human.class.getDeclaredMethod("getAge"); // 调用该方法,传入子类对象实例 String parentResult = (String) humanGetAgeMethod.invoke(obj); System.out.println(parentResult); // 输出Human's age is 21 } catch (Exception e) { e.printStackTrace(); } } }
为什么obj.super.getAge()会报错?
super是Java编译器提供的语法糖,它仅在子类内部有效,用来明确指定调用父类的成员,并非一个可以通过对象引用访问的实际成员变量或方法,因此外部代码无法通过对象.super的形式调用父类方法。
内容的提问来源于stack exchange,提问作者Aman Malakar
相关产品推荐
相关产品推荐

