简体   繁体   English

从子类调用父类中的方法

[英]Call method in parent class from child class

This might seem like a stupid question, but is it possible for an object to call a method from the object which instantiated it? 这可能看起来像一个愚蠢的问题,但是对象是否可以从实例化它的对象中调用方法?

Specifically if I have a class A which extends JFrame to provide a GUI and class B and C which are of the type JPanel with various components, which class A object changes between B and C to display different content to the user. 具体来说,如果我有一个扩展JFrame的类A来提供一个GUI和类B和C,它们是具有各种组件的JPanel类型,那么A类对象在B和C之间变化以向用户显示不同的内容。 Is it possible for object of class B to call method of class A without creating another object of class A inside B but call the upper A object which has B inside it? B类的对象是否可以调用类A的方法而不在B中创建另一个类A的对象但是调用其中包含B的上层A对象?

我看到的最简单的方法是将A传递到B和C,或者通过参数或B / C的扩展来保存A实例并且具有setter。

Looks like you need something like this. 看起来你需要这样的东西。

    class A {
        private B b;
        public void method() {
            b = new B(this);
        }
    }

    class B {
        private A a;
        public B(A a) {
            this.a = a;
        }
        void callAMethod() {
            a.method();
        }
    }
}

You can try to place reference to your A object that created B or/and C objects inside of them for example by using setters or passing them as constructor parameter. 您可以尝试在其中创建B或/和C对象的A对象的引用,例如通过使用setter或将它们作为构造函数参数传递。

class A extends JFrame{
    void someMethod(){System.out.println("methods body");}
    public static void main(String[] args) {
        A a=new A();
        B b=new B();
        b.setCreator(a);
        b.test();
    }

}
class B extends JPanel{
    private A creator;
    public void setCreator(A creator) {
        this.creator = creator;
    }

    void test(){
        creator.someMethod();
    }
}

还要考虑在Swing框架中存在不同的方法来获取组件的层次结构,如getParent()getRoot()

The best solution would be for the code doing the instantiation to pass a reference for itself to the object it is creating / has created. 最好的解决方案是执行实例化的代码将自身的引用传递给它正在创建/创建的对象。

It is theoretically possible for an object to find out which class created it (by creating an Exception and looking at its stacktrace) ... but there's no way within the executing application to find out the creating instance . 从理论上讲,对象可以找出创建它的 (通过创建Exception并查看其堆栈跟踪)......但是在执行的应用程序中找不到创建实例是没有办法的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM