What is a constructor? Explain the differences between methods and constructor.
1. A constructor is a block of code with the same name of its defining class without return type
Example Employee() {…} // The class name is Employee
2. A constructor creates an object of a class
3. The constructor sets values to the instance variables. Usually the code in the constructor is to assign values to the instance variables whenever an object is instantiated.
Differences between constructors and methods.
1. A constructor is used to create objects of a class. A method is an ordinary member in a class.
2. Constructor does not have a return type. A method should have a return type.
3. Constructor name is the name of the class. A method name should not be the name of the class
4. Constructor is invoked at the time of creation of the class. Method need to be invoked in another method by using the dot operator.
5. Constructor can not have ‘return’ statement. All methods that return non-void return type should have ‘return’ statement.
Write code to depict the use of constructor.
The following code snippet depicts the use of the constructor
It initializes the account balance and the rate of interest
public class BankAccount
{
float balance, interestRate;
public BankAccount()
{
balance = 873398.90;
interestRate = 0.08;
}
}