有没有什么方法可以在不修改方法的情况下从java中的子类对象调用父类方法 [英] is there any way to call parent class method from child class object in java without modifying methods

查看:45
本文介绍了有没有什么方法可以在不修改方法的情况下从java中的子类对象调用父类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有父类和子类,它们都有一个具有相同签名(覆盖)的方法 m1,我可以在以下场景中调用父类方法吗?我不想改变子类方法.

I have parent class and a child class, both of having a method m1 with same signature (Override), can I call parent class method in following scenario. I dont want to change child class method.

// Super class
public class Parent
{
    public void m1()
    {
        System.out.println("Parent method");
    }
}
// Sub class
public class Child extends Parent {
    @Override
    public void m1() {
        System.out.println("Child method");
    }
}
// User class
public class Kavi {
        public static void main(String[] args) {
            Parent p = new Child();
            p.m1();

        }
}

我想调用父类的 m1 方法.我知道我可以在子类方法中使用 super 来调用其父方法.但我无权更改子类的源代码.我必须从子类对象调用它.请任何人帮忙!!!在java中可以吗??

I want to call parent class m1 method. I know that I can use super in child class method to call its parent method. but I have no right to change the source code of child class. and I have to call it from child class object. please anybody help !!! is it possible in java ??

推荐答案

在创建对象时,您使用的是超类的引用,但您的对象是子类,因此在调用 m1() 方法时,将调用覆盖的方法.如果你想调用超类的方法,那么对象应该是超类.如:

While creating the Object you are using reference of Super class but your object is of child class, so while calling m1() method the overrided method will be invoked. If you want the method of the super class to be invoked then object should be of Super class. As :

Parent parent=new Parent();
parent.m1();

您可以从子类调用超类 m1() 方法.

you can invoke the super class m1() method from the child class.

@Override
public void m1() {
    super.m1();
    System.out.println("Child method");
      }

OR ELSE

import java.lang.reflect.*;
class A {
    public void method() {
        System.out.println("In a");
    }
}
class B extends A {
    @Override
    public void method() {
        System.out.println("In b");
    }
}
class M {
    public static void main( String ... args ) throws Exception {
        A b = new B();
        b.method();
        b.getClass()
     .getSuperclass()
     .getMethod("method", new Class[]{} )
     .invoke(  b.getClass().getSuperclass().newInstance() ,new Object[]{}                  ) ;

}
}

这篇关于有没有什么方法可以在不修改方法的情况下从java中的子类对象调用父类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆