Ben
Ben

Reputation: 7

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?

Upvotes: 0

Views: 2362

Answers (5)

Pshemo
Pshemo

Reputation: 124265

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();
    }
}

Upvotes: 0

Mohayemin
Mohayemin

Reputation: 3870

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();
        }
    }
}

Upvotes: 1

Stephen C
Stephen C

Reputation: 719189

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.

Upvotes: 0

PeterMmm
PeterMmm

Reputation: 24630

Consider also that in the Swing framework exists diferent ways to get the hierarchy of components like getParent() or getRoot() .

Upvotes: 0

0xCAFEBABE
0xCAFEBABE

Reputation: 5666

The easiest way I see is to pass A into both B and C, either via a parameter or an extension to B/C that holds an A instance and has a setter.

Upvotes: 1

Related Questions