What is Constructor?
When the object is created, Java calls the constructor first. Any code you have in your constructor will then get executed. You don’t need to make any special calls to aconstructor method – they happen automatically when you create a new object. Constructor methods take the same name as the class.
Rules for creating java constructor
There are basically two rules defined for the constructor.
- Constructor name must be same as its class name
- Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
- Default constructor (no-arg constructor)
- Parameterized constructor
Difference between constructor and method in javaThere are many differences between constructors and methods. They are given below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package Day2; class EmployeeTest { /** * @param args */ String name; int age; String designation; double salary; public EmployeeTest(String name){ this.name = name; } // Assign the age of the Employee to the variable age. public void empAge(int empAge){ age = empAge; } /* Assign the designation to the variable designation.*/ public void empDesignation(String empDesig){ designation = empDesig; } /* Assign the salary to the variable salary.*/ public void empSalary(double empSalary){ salary = empSalary; } /* Print the Employee details */ public void printEmployee(){ System.out.println("Name:"+ name ); System.out.println("Age:"+ age ); System.out.println("Designation:"+ designation ); System.out.println("Salary:"+ salary); } } public class Employee { public static void main(String[] args) { // TODO Auto-generated method stub /* Create two objects using constructor */ EmployeeTest empOne =new EmployeeTest("Nitin "); EmployeeTest empTwo =new EmployeeTest("Nikita "); // Invoking methods for each object created empOne.empAge(26); empOne.empDesignation("Senior Software Engineer"); empOne.empSalary(1000); empOne.printEmployee(); empTwo.empAge(21); empTwo.empDesignation("Software Engineer"); empTwo.empSalary(500); empTwo.printEmployee(); } } |