W
W
WannaCreative2016-07-03 19:14:19
JavaScript
WannaCreative, 2016-07-03 19:14:19

Why is void initialize needed?

I read that void initialize is needed for the validity of objects, but I did not understand any of this.
What's the difference between

public class Solution {

    public static String name = "Daniil";

    public void initialize(String name){
        this.name = name;
    }

    public static void main(String[] args){
        System.out.print(name);
    }

}

And this
public class Solution {

    public static void main(String[] args){
        String name = "Daniil";
        System.out.print(name);
    }

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zakharov Alexander, 2016-07-03
@WannaCreative

Usually such "things" are done not for "ordinary" object constructors, but for complex classes. For example, in C#, initialize is used in the constructors of GUI components if you extend them, for example. In this case, it is required to set many default values, the meaning of which is sometimes not clear, and is not yet important (especially when you need to somehow start for an example). But if you write your own classes, then there is a 99% chance that you will write your own initializer and validator, if you need one at all. So there is no fundamental difference in the listings in your example. Is the result the same? Just in different ways.

E
Eugene, 2016-07-04
@zolt85

The fundamental difference in the two listings is as follows:
- in the first, the variable name will be initialized when the class is loaded by the classloader and the value of this variable will be the same for all instances of this class. The level of access to the variable is public, i.e. you can get the value by accessing Solution.name. Why the initialize method is made is not clear.
- in the second, the variable name will be created and initialized when the main method is called (not before), and its scope will be limited to the scope of the main method.
something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question