In earlier articles, we had declared a class, added member method, member field and we created instance of our object to see how to use a java class and looked at constructors. In earlier article part 11, we looked initialization blocks within constructor. In this article, we cover taking it outside constructor.
Lets look to use of initialization blocks outside constructors within class in a java class.
public class CL_servers
{
public String hostname;
public String ostype;
{
hostname = "unknown";
ostype = "unknown";
}
public CL_servers() {}
public CL_servers(String arg1_hostname)
{
this.hostname = arg1_hostname;
}
public CL_servers(String arg1_hostname,String arg2_osType)
{
this();
this.hostname = arg1_hostname;
}
}
In our above class, we have 3 constructor. One sets initial state value of fields to "unknown" if our object gets created without those fields are given a value. 2nd method is overloading constructor with 1 parameter and 3rd overloaded constructor has 2 parameter.
Lets see it in Java class example.
In above example, when we create an object with both overloaded constructors, we call constructor in that 3rd overloaded one. Note that apart from constructor with no parameter which assigns "false" to object field "isCompliant" when it has no value, a initialization block has been executed to assign "unknown" to values when they are not given.