Java Constructor with programming examples
Description:
Java Constructor with programming example:- In this article, we will discuss constructors in the previous article, I have discussed how to define a class and how to create objects.
The syntax for creating an object:
1 |
Classname var_name = new Classname(); |
So this is the syntax of creating an object so you have the class name then the reference variable then new operator is used for allocating memory on the heap for the object and then class name followed by the parenthesis.
one thing that you need to keep in mind about the new operator is that so this always will not create will not allocate memory for you because memory is finite since memory is finite there are chances that it may not create it may not allocate memory for the object on the heap so there are chances that it will not allocate the memory so in case if new operator is not able to in case if JVM is not able to create a memory for the object on the heap it will give an error which is OutOfMemoryError and this error will be found during runtime the simple programs that we write may be memory will be allocated but when you are working with real-world, projects then maybe you may encounter such kind of situation.
Java Constructor:
The class name followed by parentheses is called the constructor
1 |
Classname(); |
So this is the java constructor, The java constructor is mandatory for us to give the constructor so if you just refer to the previous article that I have taught you so I have given the general form of the class. When I didn’t use the java constructor in the general form so it is not compulsory to write the java constructor in your class.
Default Java Constructor:
What will happen if you are not writing the constructor so what will happen is the compiler during compilation time the compiler will add the default constructor to your code the compiler will add the default constructor during compilation to your code. so in your source code so if you say this is your source code.
In your source code there will be no java constructor, but when this source code is converted to the byte code, so when it is converted after compilation it is converted into byte code is nothing but it is a dot class(.class) file so inside your dot class file you will be finding the default java constructor.
the default constructor means that something will not have anything in the body, so the java constructor will be having the name of the class as its name, so just it will be having the class name followed by parentheses and an open bracket and close bracket
1 2 3 4 5 |
Classname() { } |
So such type of java constructor is called as the default constructor, and if you are not mentioning one in your program the compiler will add it during compilation to your program.
Important Points of Java Constructor:
- Java constructor defines what occurs when an object of that class is created.
- Java constructor initializes an object immediately upon creation. not only initialization okay generally the widely used purpose of a constructor is to initialize an object immediately upon creation but not only for initialization.
- Java Constructor can be used for error handling and writing some other logic, and for object creation so starting a thread and calling a method. so all this you can do inside a constructor other than just initialization
- Java constructor cannot be static so you cannot say static box or static class name, so tehe constructor cannot be static abstract final and synchronized.
- Java constructor can have all access modifiers it can be default it can be public it can be protected it can be private.
- Java constructor have same name as class name.
- syntactically java constructor are similar to a method.
- Java constructor do not have explicit written type not even void so i want all of you to remember that generally if there is no written type we say void not even void, so it doesn’t have any written type in explicitly.
- implicitly the written type is the class type.
These are some very important points that we need to keep in mind before knowing about constructor.
Example1: how to use Default Java Constructor concept:
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 |
class Box { double width; double height; double depth; public static void main(String args[]) { Box obj = new Box(); System.out.println(obj.width); System.out.println(obj.height); System.out.println(obj.depth); } } |
Output:
Program Explanation:
In this example, the class is box, and inside the box class I am having three instance variables and one method which is main method, so this is the entry point of the program.
Inside the main method I have created one object and the name of the object is obj so that’s a reference variable for the object, and I have tried to print the instance variables, and you can see in the entire program I have not initialized the values of width height, and depth.
if you are not mentioning any java constructor in your entire program so the compiler will add a constructor so the constructor looks like this
1 |
Box(){} |
so it will have the name as the class name so the constructor name also will be box and i said that this will syntactically look like a method. so there will be parentheses and then there will be an open bracket and a close bracket. So this is the default constructor that the compiler will add to this program. where does this compiler add this code?
1 |
Box(){} |
into the program so there is no rule like initially there should be variables and after that, there should be java constructor and then only there should be methods there is no specific place in the class like you can give your constructor at the top then declare your I mean variables and then you can have your methods so you can jumble them but according to the good programming practices we generally give the variables at the top and then the constructor and the method so it is not mandatory that you follow the place rules of the variables methods and constructors you can give the constructor wherever you want you can write the main method before and also give the variables at the bottom so it is correct syntactically and this
1 |
Box(){} |
This is the default constructor. Which will be added into the code by the compiler during compilation so what is the purpose of this constructor? so the purpose of the constructor is “constructor initializes an object immediately upon creation”. The object name is obj. obj is holding three instance variables those are width, height, and depth.
Now the java constructor will initialize them to the default values of the primitive data types. So the default values of the double is 0.0 so it will add for width it will add 0.0 and for height, it will add 0.0 and for depth, it will initialize to 0.0.
Example2: how to use java constructor in programming:
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import java.time.*; public class EmployeeTest { public static void main(String args[]) { Employee[] staff = new Employee[3]; staff[0] = new Employee("Fawad khan",40000,2020,11,24); staff[1] = new Employee("Engr Fahad",60000,2019,03,01); staff[2] = new Employee("Abc",50000,2017,06,14); for(Employee e : staff) e.raiseSalary(5); for (Employee e : staff) System.out.println("name="+e.getName()+",salary="+e.getSalary()+",hireDay="+e.getHireDay()); } } class Employee { private String name; private double salary; private LocalDate hireDay; public Employee(String n, double s, int year, int month, int day) { name=n; salary=s; hireDay=LocalDate.of(year,month,day); } public String getName() { return name; } public double getSalary() { return salary; } public LocalDate getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent /100; salary +=raise; } } |
Output:
Java Constructor with no arguments:
Many classes contain a no-argument constructor that creates an object, a state which is set appropriately by default. The example below is a no-argument constructor for the Employee class.
1 2 3 4 5 6 7 8 9 10 11 |
public Employee() { name = ""; salary = 0; hireDay = new Date(); } |
If constructors are not defined at all in the class, then it is automatically created java constructor with no arguments. In this java constructor, all fields of the instance are assigned their default values. So, all numerical values, contained in the instance fields will be equal to zero, boolean variables false, object variables null.
If the class has at least one constructor and the constructor is not explicitly defined without arguments, you cannot create objects without providing arguments. For example, the Employee class in Example2 has one constructor as follows:
1 |
Employee(String name, double salary, int y, int m, int d ) |
In this version, the data of the class cannot be created as an object, the fields of which took would be the default. In other words, the following call will result in an error:
1 |
e = new Employee(); |
Java Constructor Parameter names:
By creating even an elementary constructor, it is difficult to choose appropriate names for its parameters. Usually, as parameter names are represented by individual letters, as shown below.
1 2 3 4 5 6 7 8 9 |
public Employee(String n, double s) { name = n; salary = s; } |
But the disadvantage of this approach is that, while reading the program, it is impossible to understand what the parameters n and s mean. Some programs add meaningful parameter names that are prefixed with “a”.
1 2 3 4 5 6 7 8 9 |
public Employee (String aName, double aSalary) { name= aName; salary = aSalary; } |
This code is pretty self-explanatory. Anyone reading it can immediately determine what is the meaning of the parameter. To use it, you should be aware that parameters hide the instance fields with the same names. So, if you call the method with the salary parameter, then the salary reference will be on the parameter, not on the instance field. Field access instance is implemented using the expression this. salary. Recall that the this keyword denotes an implicit parameter, i.e. object to be constructed as is demonstrated in the following example:
1 2 3 4 5 6 7 8 9 |
Public Employee(String name, double salary) { this.name = name; this.salary = salary; } |
Calling one java constructor from another:
this keyword denotes an implicit method parameter. But this the word has one more purpose. If the first operator of the java constructor is this (…), then another java constructor of the same class is called. Below is a typical example of this.
1 2 3 4 5 6 7 8 9 10 11 |
public Employee (double s) { // call constructor Employee (String, double) this ("Employee" + nextid, s); nextid ++; } |
If the operation new Employee (60000) is executed, then the constructor Employee (double) calls the constructor Employee (String, double). Use the this keyword for calling another constructor is very convenient – you just need to write general code to construct an object once.
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
import java.util.*; public class ConstructorTest { public static void main(String[] args) { // fill the staff array with three // objects of type Employee var staff = new Employee[3]; staff[0] = new Employee("Harray", 40000); staff[1] = new Employee(8333); staff[2] = new Employee(); // display data about all objects of type Employee for(Employee e : staff) System.out.println("name=" + e.getName()+",id="+e.getId()+ ",salary="+e.getSalary()); } } class Employee { private static int nextId; private int id; private String name=""; //initialization private double salary; // instance fields // static initialization block static { var generator = new Random(); // set an arbitrary number 0-999 in the nextld field nextId = generator.nextInt(10000); } // object initialization block { id = nextId; nextId++; } // three overloaded constructors public Employee(String n, double s) { name = n; salary= s; } public Employee(double s) { // call constructor Employee (String, double) this("Employee #" + nextId, s); } // constructor with no arguments public Employee() { // the name field is initialized with an empty string "" - // salary field is not set explicitly, see above; // and is initialized to zero // the id field is initialized in the initialization block } public String getName() { return name; } public double getSalary() { return salary; } public int getId() { return id; } } |