In earlier parts, 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 this article, we will see another method of using constructors to initialize an object in declaration with initial state.
In Java Class, while we create an object, we can provide an initial state value to its fields if we added before its overloaded constructor.
Lets look to use of it in a java class.
public class CL_servers
{
String ostype;
public String hostname;
public CL_servers()
{
hostname = "unknown";
}
public CL_servers(String arg1_hostname)
{
this.hostname = arg1_hostname;
}
}
In our above class, we have two constructor. One sets initial state value of field hostname to "unknown" if our object gets created without a name. Second method is overloading constructor with 1 parameter. If we provide it during object instantiating, that method will allow us to set initial state in initialization.
Lets see it in Java class example.
In above example, we created an object and assigned its value with 1 parameter constructor method.