A regular constructor for an object is run once. It is only run when the object is created, it is initialized. All constructors are named based on the class’ name, if I have a class called Computer, my constructor’s method is also Computer. This is a normal constructor and this causes a plain vanilla initialization. In addition to these, there are two other type of initialization that you may want to use in programs.
Static Initialization
Static methods are accessible anytime from anywhere, you don’t need an object to access it. Static variables are the same too.
class MyClass { public static int number = 10; public static int getNumber() { return number; } }
For example, let’s pretend that number wasn’t initialized but it needed to be. Since it’s a static variable, you cannot set it in the class constructor. There is a solution though and it is called the Static Initializer. I’m not making this up either.
class MyClass2 { public static int number; static { number = 10; } public static int getNumber() { return number; } }
The difference? You can create complex objects just once upon initialization. This could be helpful if you need a persistent data connection or if you have a universal file writer or file reader. At an elementary level of java, there may not be many uses for this but it is good to know.
Instance Initialization
Normally the code that is first executed when an object is created is in the object’s constructor. Like static initialization, which runs just once, you can have some code run before the object’s constructor code.
class InstanceInitialization { // Instance initalizer, clever, isn't it? { System.out.println("I'm the instance initalizer."); } public InstanceInitialization() { System.out.println("I'm the constructor!"); } }
Again, what’s the point of this? This can be clever for setting up a universal initialization place for data members. You might consider using this when the initialization for parts of constructors are the same. You can move the repeated initialization to the instance initializer.
So now you know about constructors, static initialization and instance initialization.