开发者

Initialize an object in java

开发者 https://www.devze.com 2023-02-01 12:22 出处:网络
Is it the right Way we initialise the the object? I have a class Sample I want to initialise the Object in my Sample1 Class

Is it the right Way we initialise the the object?

I have a class Sample I want to initialise the Object in my Sample1 Class After intialisation I dont require to use the object of Sample Class.

In that Case Can I initialise that object as new Sample(); instead of Sample s = new Sample(); if I am not going to use s anywhere in my Sample1 Class

My questio开发者_如何学Cn, is this a good practice to do that? will there be any after affects


I commonly encounter the dilemma you describe in the main method of my applications; I want to initialize the application class, but don't need a reference to it after that, for example:

public class MyApplication {

    public MyApplication() {
        // Initialize and run application
    }

    public static void main(String[] args) {
        new MyApplication();
    }
}

Some consider this a code smell. However adding a local variable or field just to keep a useless reference also seems wrong. The short answer to your question: there are no negative side effects and whether the design is bad or not is up for debate.

One way 'around' this is to be more puristic about your constructor. One could reason constructors should be used for initialization only, not for starting up your application. Then you could separate these concerns as follows:

public class MyApplication {

    public MyApplication() {
        // Initialize application
    }

    public void run() {
        // Run application
    }

    public static void main(String[] args) {
        MyApplication app = new MyApplication();
        app.run();
    }
}

You can defend this as a valid design decision, and it also solves your unreferenced instance problem at the same time!


If you dont need it why initialise it ?


You can do that but unless you make Sample a singleton you will be initializing it every time you create an object for it. I am not sure if this is what you want as you have not specified what you are initializing. There might be a better alternate way. Specify what you are initialzing or what is your requirement so that people can provide a more specific answer.


Yeah, that's alright. If you do not have any state (instance variable), you can very well go with a static method that does what your constructor is doing. And you just do, SampleClass.myMethod()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号