Can a Java class be aware of its instance?

Is there a way for a Java class to be aware of its instance? For instance:

public class Foo() {

    public Foo() {
        // can I get Bar.myInteger from here somehow 
        // without passing it in to the constructor?
    }
}

public class Bar {
    private int myInteger;

    public Bar() {
        myInteger = 0;

        Foo foo = new Foo();
    }
}
+3
source share
11 answers

Is there any specific reason why you don't want to pass anything in the constructor?

Simply put, this violates the principle of encapsulation ... and perhaps a few others.

+8
source

With inner classes you can.

public class Bar {

   private int myInteger;

   public class Foo() {

        public Foo() {
             // you can access myInteger
        }
    }


    public Bar() {
        myInteger = 0;
        Foo foo = new Foo();
    }
}
+5
source

, .

?

+2

:

Throwable t = new Throwable();
t.fillInStackTrace();
StackTraceElement[] stt = t.getStackTrace();

stt[].

+2

, . , , . .

+2

, myInteger , Foo , Bar, myInteger . , .

, Foo .

0

, , getter/setter. - .

0

"Instantiators" Factory. "" , , .

, . ? ?

0

Foo Bar, Bar.

0

, :


public class Bar {
    private int myInteger;
    public Bar() {
        myInteger = 0;
        Foo foo = new Foo();
    }
    class Foo {
        Foo() {
            int i = Bar.this.myInteger;
        }
    }
}

.

0

Keeping simplicity ... 1. If Foo should always know myInteger from Bar, pass it to the constructor.
2. If Foo only occasionally needs to know myInteger, then call the setter after the constructor.

If Foo requires more than myInteger, i.e. the whole Bar object, then Bar can pass itself using the keyword "this".

public class Foo
{
  public Foo(Bar bar)
  { 
    //Do something with Bar 
  }
}

// Somewhere in the bar (in the non-stationary method)
  new Foo (this);

0
source

Source: https://habr.com/ru/post/1734907/


All Articles