Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from instance

Tags:

java

oop

Let's say I have two classes, A and B, in turn have some methods, something() and nothing() and an instance of B is created in A, as

public class A {

    public A() {
        B b = new B();
        b.nothing();
    }

    public void something() {
        ...
    }
}

A calling b.nothing() is all standard stuff, but is there any means which by instance b can call a.something(), assuming the instance of A is called a. If not, why is this conceptually wrong?

like image 533
Theodor Avatar asked Sep 03 '26 13:09

Theodor


2 Answers

I don't think there's anything conceptually wrong with this.

However, for the mechanics to work, b needs to know which instance of A to call something() on. For this, either B's constructor, or its nothing() method, needs to take an A reference as an argument.

example 1:

public class B {
  public void nothing(A a) {
    ...
    a.something();
    ...
  }
}

example 2:

public class B {
  private final A a;
  public B(A a) {
    this.a = a;
  }
  public void nothing() {
    ...
    this.a.something();
    ...
  }
}

example 3:

There is a third way, applicable in some circumstances. If B is an inner class of A, it has an implicit reference to its associated instance of A.

public class A {
  public void something() { ... }
  public class B {
      public void nothing() {
        ...
        something();
        ...
      }
  }

}

like image 99
NPE Avatar answered Sep 05 '26 02:09

NPE


is there any means which by instance b can call a.something()

You can't get hold of the caller in a method so, no, there's no way to do that.

If not, why is this conceptually wrong?

Two issues come to my mind immediately:

  • What would the type of the caller be? Since anyone could call b.nothing(), you can't assume more than that it's an Object which would result in lots of ugly down casts.

  • The implementation of b.nothing() shouldn't care about who's calling him. What happens if you refactor A and move the call to b.nothing() to some other class? It would be quite surprising if b.nothing() all of a sudden stopped working.

like image 30
aioobe Avatar answered Sep 05 '26 02:09

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!