Wednesday, January 1, 2020

Constructors

Constructors 


Class Constructor


A constructor is a block of statements that can be used to initialize an object(see Classes and Objects) before the reference to the object is returned by the "new" keyword.

Points to remember about Constructors

 The constructor looks like a method(Or we can say that it is a special kind of a method)
  • The constructor has the same name as the class name.
  • The constructor doesn't have any return type as a method.
  • Constructors can have access specifiers(public, private, protected or default)
  • The constructor is automatically invoked when an object of that class is created.
  • Constructors can be overloaded(means a class can have multiple constructors).
  • In absence of a defined constructor default constructor( constructor of its superclass) may be used. 
  • Constructors are not the members of the class, so constructors are not inherited.
  • We can use the "super" keyword to access the superclass constructors (Constructor chaining is also possible in Java)
  • The "super" can be invoked only in the first line of a constructor block.
  • We can also use the "this" keyword to refer to constructors in the current class.
  • Constructors can be parameterized or not parameterized.


java class constructors


For example,

Creating a Class Constructor
Creating a Class Constructor


Java Constructor Example


/**********constructor example*************/
public class Employee {
int emp_id; //Instance variables
String emp_name;
int basic_sal;
int HRA;
int income_tax;
//Constructor overloading is possible
Employee() //Constructor
{
      this.emp_id = 0;
      this.emp_name = "";
      this.basic_sal = 0;
      HRA = 0;
      this.income_tax = 0;
}//Another Constructor
public Employee(int emp_id, String emp_name, int basic_sal, int hRA, int income_tax) {
      super();//invoke super class constructor
      this.emp_id = emp_id;
      this.emp_name = emp_name;
      this.basic_sal = basic_sal;
      HRA = hRA;
      this.income_tax = income_tax;
}
//a method
public void displaySalary()
{
System.out.println(emp_name+" salary is "+(basic_sal+HRA-income_tax));
}
}


Video Tutorial