Prev Next

Java / Constructor

1. What is a Constructor? 2. Rules for creating a Java constructor. 3. Types of Java constructor. 4. Java Default Constructor. 5. Java parameterized constructor. 6. Advantages of parameterized constructor. 7. What happens when the developer does not implement default constructor? 8. Purpose of default constructor. 9. Constructor Overloading in Java. 10. Copy-Constructor. 11. Difference between constructor and method in Java. 12. What are pass by reference and pass by value? 13. Can constructor perform other tasks instead of initialization? 14. Can a constructor call/invoke a static method? 15. Can a constructor invoke a non-static/instance method? 16. Can abstract class have constructors? 17. What is the access modifier of the Default constructor? 18. Can the class with private constructor be extended? 19. Can the inner class with private constructor be extended? 20. Can you use this() and super() both together in a constructor? 21. Can constructor be synchronized in Java? 22. Is constructor inherited? 23. Can a constructor be final? 24. Can we call the constructor of a class more than once for an object in Java? 25. Is constructor called when cloning in Java? 26. Different ways to create an object in Java. 27. Difference between Class.newInstance() and Constructor.newInstance(). 28. How to Initialize class with Class.forName() that has parameterized constructor? 29. Can you define a method with the same name as the class? 30. What happens when we add a return type to the constructor? 31. Is Constructor definition mandatory? 32. If a class has an explicit constructor, does compiler create default constructor? 33. Can we throw exceptions from a constructor? 34. What are the access modifiers that cannot be applied to a constructor? 35. What is constructor chaining? 36. How do I call subclass constructor from superclass constructor? 37. What is No-arg constructor or default constructor.? 38. Can you declare Constructor as final in Java?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

What is a 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.

Rules for creating a Java constructor.
  • Constructor name must match its class name.
  • Constructor must not have any return type.
Types of Java constructor.

Two types of constructors:

  1. Default constructor (no-arg constructor).
  2. Parametrized constructor.
Java Default 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();

	}
}

Java parameterized constructor.

A constructor that takes arguments is referred as parameterized constructor.

Advantages of parameterized constructor.

Customize initializing the property state of the object using user defined values thus eliminates using default values.

What happens when the developer does not implement default constructor?

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.

Purpose of 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.

Constructor Overloading in Java.

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.

Copy-Constructor.

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);
               }
 
}

Difference between constructor and method in Java.

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.

What are pass by reference and pass by value?

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.

Can constructor perform other tasks instead of initialization?

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.

Can a constructor call/invoke a static method?

Yes.

Can a constructor invoke a non-static/instance method?

Yes.

Can abstract class have constructors?

Yes, abstract class can define constructor altough abstract class cannot be initiated.

What is the access modifier of the Default constructor?

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.

Can the class with private constructor be extended?

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();
    }
}

Can the inner class with private constructor be extended?

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

Can you use this() and super() both together in a constructor?

No. Either this or super must be in first statement so we can have either one at a time and not both.

Can constructor be synchronized in Java?

No. constructor cannot be synchronized.

Is constructor inherited?

No, constructor is not inherited.

Can a constructor be final?

No, constructor cannot be final.

Can we call the constructor of a class more than once for an object in Java?

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.

Is constructor called when cloning in Java?

No. It doesn't invoke constructor.

Different ways to create an object in Java.

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();
Difference between Class.newInstance() and 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)
How to Initialize class with Class.forName() that has parameterized constructor?

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");

Can you define a method with the same name as the class?

Yes, it is allowed. However not recommended due to coding standards.

What happens when we add a return type to the constructor?

JVM considers it as a method instead. Only the return type differentiates between constructor and the method.

Is Constructor definition mandatory?

Not at all However compiler will define one (default constructor) if not defined explicitly.

If a class has an explicit constructor, does compiler create default constructor?

No. compiler creates default constructor only if there is no explicit constructor.

Can we throw exceptions from a constructor?

Yes, constructor can have throws clause.

What are the access modifiers that cannot be applied to a constructor?

final ,static, abstract and synchronized keywords cannot be applied to a constructor.

What is constructor chaining?

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.

How do I call subclass constructor from superclass constructor?

No. This is not possible.

What is No-arg constructor or default constructor.?

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
    {
        
    }
}
Can you declare Constructor as final in Java?

No. It results in compile time error.

«
»
Interface

Comments & Discussions