wade712vn
wade712vn

Reputation: 63

Java: invoking method

In Java, I have something like this

public class A {
    private String title;
    public A () { 
    // do something
    }

    public void run () {
        B b = new B();
        b.run();
    }

    public void changeTitle(String newTitle) {
        this.title = newTitle;
    } 
}


public class B {
   public B() {
   // do something
   }
   public void run() {

   }
}

My question is in method run() of B, is it possible to invoke method changeTitle() in A to change the title of the instance of A that instantiates B?

Thanks

Upvotes: 0

Views: 204

Answers (7)

Ralph
Ralph

Reputation: 120761

Is B is a non static inner class of A you van invoke the mehods of A (and access its fieldes).

Upvotes: 0

subsub
subsub

Reputation: 1857

no. As such an instance of B does not know who created it.

However with B as:

public class B {
   private A creator;

   public B(A creator) {
      this.creator = creator;
      // do something
    ...
  }

and creating new B(this) in A.run(), B could call creator.changeTitle("whatever") in its run() method.

Upvotes: 0

Gareth McCaughan
Gareth McCaughan

Reputation: 19971

Not unless you arrange for instances of B to know what instance of A they should do that to (e.g., by passing that into the constructor for B and remembering it).

If you're doing something like this then you should consider, e.g., what you want to happen if an instance of B is created by something other than an instance of A.

Upvotes: 0

Jeff Foster
Jeff Foster

Reputation: 44696

B can only invoke methods on A if it contains a reference to an instance of A. You could pass an instance of A into B to achieve this.

public void run () {
    B b = new B(this);
    b.run();
}

public class B {
   private A a;
   public B(A a) {
       this.a = a;
       a.changeTitle("Ha!");
  }
}

Upvotes: 1

Jake Kalstad
Jake Kalstad

Reputation: 2065

if B accepts a type A in its constructor, and when you say new B, pass in 'this' similar to

public void run () {
    B b = new B(this);
    b.run();
}

now you have a copy of the A object your working with.

Upvotes: 1

Ingo
Ingo

Reputation: 36329

This will only be possible if you pass this as argument when you invoke B's run() method.

Upvotes: 0

Isaac Truett
Isaac Truett

Reputation: 8874

Sure. Pass an instance of A in the constructor for B.

Upvotes: 0

Related Questions