|
Now that you know how a class and its members are declared, let us see how you can create objects from this class. Java class provides special methods called as constructors. Constructors are methods that have same name as the class and they do not specify any return type (not even void). Java class provides them to allow the creation and initialization of created objects. You need to explicitly write a constructor for your Java class only if want to initialize something (like assigning a value to one of its member variables) when the object is being created. For example, you can write a constructor for Account class that will help in creating Account objects with initial balance of 100 as-
public class Account {
private float balance;
public Account(float initialBalance) {
balance = initialBalance;
}
}
If you need to initialize objects in different ways with different values, you can declare multiple constructors. Each of these multiple constructors takes different arguments. These multiple constructors are called as overloaded constructors. Overloading means that the number and type of their arguments differentiate them from each another. For example, the String class in the java.lang provides several different constructors:
public String(String) {}
public String(char) {}
public String(byte[],int) {}
Each of these constructors takes different arguments with which a new String object will be created and get its initial state.