简体   繁体   中英

I have a question about some code in java application

What is the difference between these two definitions?

public class MainClass {
    //definition one
    private static MainClass main = new MainClass();
    //definition two
    private static MainClass main2 = MainClass.getMain2();

    public static void main(String[] args) {

    }

    private static MainClass getMain2() {
        return main2;
    }

}

Which one is better?

I think your code is wrong. This method should be in some other class. It should be like

private static MainClass getMain2() {
    return new MainClass();
}

It's called dependency injection.

Your code should be like below

public class MainClass {
    //definition one
    private static MainClass main = new MainClass();
    //definition two  
    private static MainClass main2 = MainClass.getMain2();

    public static void main(String[] args) {

    }

    //constructor injection
    private static MainClass( MainClass a) {
       this.main2  = a;
    }
    //Or in place of constructor injection you can use Setter injection
    public static setMain2( MainClass a) {
        this.main2  = main2;
    }

@Thiago Arrais answered on What is dependency injection? is quite easy to understand without serious coding/framework knowledge -

The best definition I've found so far is one by James Shore:

"Dependency Injection" is a 25-dollar term for a 5-cent concept.Dependency injection means giving an object its instance variables.

There is an article by Martin Fowler that may prove useful, too.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (eg Spring) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM