Java constructors

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;
    }
}
Java class member
Java class member - What is instance members?, What is instance variable?, What is instance method?, What is static member?, What is static variable?...
Java packages
Java packages - What are Java packages? Explain the importance of Java packages., Steps for creating a package in Java, Explain the packages access specifier, i.e. private, protected, public, default...
Java garbage collector
Java garbage collector - Explain Java Garbage collector. Why garbage collection? Brief explanation of Garbage collection algorithms., Explain the importance of finalizers in Java...
Post your comment