Charlie Landrigan
Charlie Landrigan

Reputation: 71

Is a class that creates an instance of another its parent?

If class A creates an instance of class B, then in class B can I run a method from class A? sorry if the question is poorly worded, I don't know how else I could say it.

Upvotes: 0

Views: 46

Answers (2)

Sandman
Sandman

Reputation: 2745

In class B you can call methods of class A only if A's methods are visible to B. It doesn't matter who created an instance of B.

This tutorial might help: http://www.tutorialspoint.com/java/java_access_modifiers.htm

So you can call it if the method is one of the following:

  • public
  • protected (and B is a subclass of A or B is in the same package as A)
  • no modifier (and B is in the same package as A)

Upvotes: 0

Deepak Agrawal
Deepak Agrawal

Reputation: 290

In the below code, Class A creates an instance of Class B and you can call Class A's method from Class B's method.

class A {
    public void getA() {
         System.out.println("In A");
    }

    public static void main(String[] args) {
        B b = new B();
        b.getB();
    }

}

class B {
    public void getB() {
        System.out.println("In B");
        A a = new A();
        a.getA();
    }

}

Output:

In B

In A

Upvotes: 1

Related Questions