Java类是否可以了解其实例化器?

Mic*_*rdo 3 java constructor

有没有办法让Java类了解其实例化器?例如:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Pow*_*ord 8

有什么特别的原因你不想在构造函数中传递任何东西吗?

简而言之,这违反了封装原则......也可能违反其他几个原则.


ewe*_*nli 5

有了内部课程,你可以.

public class Bar {

   private int myInteger;

   public class Foo() {

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


    public Bar() {
        myInteger = 0;
        Foo foo = new Foo();
    }
}
Run Code Online (Sandbox Code Playgroud)