Why constructors are used in java




















Thus, once the class is compiled it will always at least have a no-argument constructor. If you do define a constructor for your class, then the Java compiler will not insert the default no-argument constructor into your class. As you have already seen, it is possible for a Java constructor to take parameters. These parameters can then be used to initialize the internal state fields of the newly created object. Here is an example:.

In this example the Java constructor declaration is marked in bold. As you can see, three parameters are declared: first , last and year. Inside the body of the constructor the values of these three parameters are assigned to the fields of the Employee object. The line breaks after each parameter are optional. The Java compiler ignores line breaks here. You can also write the parameter declaration in a single line if you want, like this:.

To call this constructor that takes three parameters, you would instantiate an Employee object like this:. The parameters are passed to the constructor inside the parentheses after the class name on the right side of the equal sign.

The object is then created, and the constructor executed. After execution of the above constructor, the fields initialized by the constructor will have the values of the parameters passed to the constructor. A Java constructor parameter can have the same name as a field.

If a constructor parameter has the same name as a field, the Java compiler has problems knowing which you refer to. By default, if a parameter or local variable has the same name as a field in the same class, the parameter or local variable "shadows" for the field. Look at this constructor example:. Inside the constructor of the Employee class the firstName , lastName and birthYear identifiers now refer to the constructor parameters, not to the Employee fields with the same names.

Thus, the constructor now just sets the parameters equal to themselves. The Employee fields are never initialized. To signal to the Java compiler that you mean the fields of the Employee class and not the parameters, put the this keyword and a dot in front of the field name. Here is how the Java constructor declaration from before looks with that change:. You call a constructor when you create a new instance of the class containing the constructor.

Here is a Java constructor call example:. This example invokes calls the no-argument constructor for MyClass as defined earlier in this text. In case you want to pass parameters to the constructor, you include the parameters between the parentheses after the class name, like this:.

This example passes one parameter to the MyClass constructor that takes an int as parameter. In Java it is possible to call a constructor from inside another constructor. When you call a constructor from inside another constructor, you use the this keyword to refer to the constructor. Here is an example of calling one constructor from within another constructor in Java:. Notice the second constructor definition. Inside the body of the constructor you find this Java statement:.

The this keyword followed by parentheses and parameters means that another constructor in the same Java class is being called. Which other constructor that is being called depends on what parameters you pass to the constructor call inside the parentheses after the this keyword.

In this example it is the first constructor in the class that is being called. In Java a class can extend another class. When a class extends another class it is also said to "inherit" from the class it extends. The class that extends is called the subclass, and the class being extended is called the superclass. Inheritance is covered in more detail in my tutorial about inheritance in Java.

If your class has a superclass or parent class then its constructor will be executed before your class. Similarly, if you have more than one constructor in your class, you can call them from your constructor. This is known as constructor chaining and you use this and super to call constructor from same class and parent class respectively.

You can use public, private, protected access modifiers with constructor or can even leave them without any parameter, in that case, it will use default access, which is at package-private level. Private constructors are special, because if you make your constructor private, then no one can call it from outside that class, which means no external way to create instance of that class.

This also prevents a class from being subclasses because by default first line of constructor has a call to super , no argument constructor of parent class, if you make that private, it will not be accessible on child class and compiler will throw error.

Private constructor has another special use, in singleton design pattern , where goal is to keep just one instance of that class. Singleton creates instance by itself, caches it and provides a getInstance method to make that instance available to outside world. Also, you cannot make constructor abstract, synchronized or final, those are illegal keyword for constructor and using them there will be error at compile time.

Some facts about Constructor in Java There are lot facts about constructor you as a Java developer should know, this will help you to read and understand existing Java code in your organization or from any open source library. Constructor can be overloaded This means you can have more than one constructor in your class all with the same name until they have different method signature, which comprises type of argument and order type of argument. Here is an example of constructor overloading.

Here we have three constructors but all with a different set of parameters, make sure you follow these overloading best practices to avoid introducing tricky bugs in your code. This also flows nicely when you call one constructor from other. You can see the example of overloaded constructor in JDK also, for example, String class got a couple of the overloaded constructors, just look their Java documentation. There is two groups of people, one who likes setter based injection and other who are purist and use a constructor, I am from that second group.

IMHO constructor highlights dependency better than Setter injection and it also enforces the order of initialization. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.

See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Skip to content. Change Language. Related Articles. Basics of Java. Operators in Java. Packages in Java. Flow Control in Java. Loops in Java. Jump Statements in Java. Arrays in Java.

Strings in Java. OOPS in Java. Constructors in Java. Interfaces in Java. Keywords in Java. Exception Handling in Java. Collection Framework. Multi-threading in Java. Table of Contents. Save Article. Improve Article. Like Article.



0コメント

  • 1000 / 1000