Java / Constructor
A constructor is a construct similar to java method without any return type.
A constructor gets invoked when a new object is created. Every class has a constructor.
In case the developer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class.
- Constructor name must match its class name.
- Constructor must not have any return type.
Two types of constructors:
- Default constructor (no-arg constructor).
- Parametrized constructor.
The constructor that takes no parameters is termed as default constructor.
package com.javatutorials.urlshort; public class Fruit { Fruit() { // No parameters mentioned at open and close parenthesis. This is // the default constructor. System.out.println(" Example of a default constructor."); } public static void main(String[] str) { Fruit fruit = new Fruit(); } }
A constructor that takes arguments is referred as parameterized constructor.
Customize initializing the property state of the object using user defined values thus eliminates using default values.
If there is no constructor in a class, compiler automatically creates a default constructor.
When there are parameterized constructors implemented, compile will not create the default constructor.
Default constructor initializes the instance variables to its default values if not initalized explicitly depending on the type.
For objects, default constructor initializes it to null, int with 0.
In the below example, make String variable is initialized to null, numberofSeats to 0 and isItOldModel to false.
public class Car { String make; int numberofSeats; boolean isItOldModel; @Override public String toString() { return "Car make is " + make + " and it has " + numberofSeats + " seats and is it old model? " + isItOldModel + "."; } public static void main(String[] args) { Car newCar = new Car(); System.out.println(newCar); } }
Output:
Car make is null and it has 0 seats and is it old model? false.
The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list.
Java supports copy constructor like C++, however Java doesn't create a default copy constructor if the developer does not provide its implementation.
public class Apple { String color; String size; Apple(String color, String size) { this.color = color; this.size = size; } Apple(Apple appleObj) { this.color = appleObj.color; this.size = appleObj.size; } @Override public String toString() { return "Apple of (" + color + " , " + size + ")"; } public static void main(String[] str) { Apple greenApple = new Apple("Green", "small"); Apple redApple = new Apple("Red", "large"); Apple anotherGreenApple = new Apple(greenApple); System.out.println(greenApple); System.out.println(redApple); System.out.println(anotherGreenApple); } }
Java Constructor. | Java Method. |
Constructor initialize the state of an object. | Method exhibits the behavior of an object. |
Constructor must not have return type. | Method must have return type. |
Constructor is invoked implicitly. | Method is invoked explicitly. |
In case of default constructor, the java compiler provides a default constructor if you don't have any constructor. | Method is not provided by compiler in any case. |
Constructor name must be same as the class name. | Method name may or may not be same as class name. |
When an object is passed by value, an exact copy of the object is passed. Thus, if changes are made to that object, it doesn't affect the original object.
When an object is passed by reference, the actual object is not passed, instead a reference of the object is passed. Any changes made by the external method, affects the original object.
Yes. In addition to initializing the state of an object, construct may initialize threads, invoke methods etc. Constructor exhibits behaviour as same as any Java method in terms of activities that it can perform.
Yes.
Yes.
Yes, abstract class can define constructor altough abstract class cannot be initiated.
No, in case of outer classes.
The below program will generate compile time error.
package org.javatutorials.accessModifer.protectedPackage;
class ClassWithPrivateConstructor { private ClassWithPrivateConstructor() { System.out.println("Hello from ClassWithPrivateConstructor"); } } public class ExtendingClass extends ClassWithPrivateConstructor { public ExtendingClass() { System.out.println("Hello from ExtendingClass"); } public static void main(String args[]) { new ExtendingClass(); } }
It depends on the Class's access modifier. If the Class declared as public, then the default constructor access modifier will be public. If the class is protected, then default constructor is protected. The same rule applies for default access and private.
Yes.
package org.javatutorials.accessModifer.protectedPackage; public class PrivateConstructorInnerClass { class Parent { private Parent() { System.out.println("Hello from Parent"); } } class Child extends Parent { public Child() { System.out.println("Hello from Child"); } } public static void main(String[] str) { PrivateConstructorInnerClass pc = new PrivateConstructorInnerClass(); pc.new Child(); } }
Output:
Hello from Parent
Hello from Child
No. Either this or super must be in first statement so we can have either one at a time and not both.
No. constructor cannot be synchronized.
No, constructor is not inherited.
No, constructor cannot be final.
Constructor is called automatically when we create an object using new keyword. It is called only once for an object at the time of object creation and hence, we cannot invoke the constructor again for an object after it is created.
No. It doesn't invoke constructor.
There are 5 different ways to create an object in Java.
Using new
keyword.
MyObject object = new MyObject();
Using Class.forName()
.
Quiz object = (Quiz) Class.forName("net.javapedia.quiz.model.Quiz").newInstance();
Using clone()
.
Quiz object1 = new Quiz(); Quiz object2 = (Quiz ) object1.clone();
Using object deserialization.
ObjectInputStream inStream = new ObjectInputStream(myInputStream ); Quizobject = (Quiz) inStream.readObject();
Using Reflection newInstance()
method of Constructor.
Constructor<Quiz> constructor = Quiz.class.getConstructor(); Quiz quiz = constructor.newInstance();
The Class.newInstance() method can only invoke a no-arg constructor.
Quiz object = (Quiz) Class.forName("net.javapedia.quiz.model.Quiz").newInstance();
To create objects using reflection with parameterized constructor you need to use Constructor.newInstance().
final Employee emp = Employee.class.getConstructor( int.class, int.class, double.class).newInstance(_xval1,_xval2,_pval)
Use Class.getConstructor()
and call Constructor.newInstance()
method.
For example, take the below constructor for Employee class which take 2 arguments.
public Employee(int empId, String name) { }
We need to invoke getConstructor method by passing argument values as shown below.
Constructor empC = Class.forName("Employee").getConstructor(Integer.TYPE, String.class); Employee employee= (Employee) empC.newInstance(345, "John Smith");
Yes, it is allowed. However not recommended due to coding standards.
JVM considers it as a method instead. Only the return type differentiates between constructor and the method.
Not at all However compiler will define one (default constructor) if not defined explicitly.
No. compiler creates default constructor only if there is no explicit constructor.
Yes, constructor can have throws clause.
final ,static, abstract and synchronized keywords cannot be applied to a constructor.
Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor while super() is used to call super class constructor.
No. This is not possible.
Constructor without arguments is called the no-arg constructor. Default constructor in Java is always a no-arg constructor and it is created by the compiler when no explicit constructor exists.
public class MyClass { public MyClass() //No-arg constructor { } }
No. It results in compile time error.