简体   繁体   中英

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. 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?

我看到的最简单的方法是将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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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