• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Top 17 Core Java Interview Questions on Constructors

February 26, 2016 by javainterviewpoint 5 Comments

1. What is a Constructor in Java?

Constructor is just like a method in Java that is used to initialize the state of an object and will be invoked during the time of object creation.

2. What are the Rules for defining a constructor?

  1. Constructor name should be the same as the class name
  2. It cannot contain any return type
  3. It can have all Access Modifiers are allowed (private , public, protected, default)
  4. It Cannot have any Non Access Modifiers (final ,static, abstract, synchronized)
  5. No return statement is allowed
  6. It can take any number of parameters
  7. Constructor can throw exception, we can have throws clause

3. What is the use of Private Constructors in Java?

When we use private for a constructor then object for the class can only be created internally within the class, no outside class can create object for this class. Using this we can restrict the caller from creating objects.

class PrivateConstructorExample
{
    /**
     * Private Constructor for preventing object creation
    from outside class
    **/
    private PrivateConstructorExample(){ }
    
    public void disp()
    {
        System.out.println("disp() method called");
    }
}
public class Sample 
{
    public static void main(String args[])
    {
        //Creating the object for the Private Constructor class
        PrivateConstructorExample pc = new PrivateConstructorExample();
        
        pc.disp();
    }
}

When we run the above code we will be getting the below exception.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The constructor PrivateConstructorExample() is not visible

	at Sample.main(Sample.java:19)

4. Can we have a Constructor in an Interface?

No, We cannot have a Constructor defined in an Interface.

5. What is Constructor Chaining in Java?

Constructor Chaining is nothing but calling one Constructor from another. this keyword is used to call the current class constructor and super keyword is used to call the parent class constructor.

class Parent
{
    public Parent()
    {
        System.out.println("Parent class no-args constructor called");
    }
    public Parent(String name)
    {
        System.out.println("Parent class Parameterized constructor called by "+name);
    }
}
public class Child extends Parent
{
    public Child()
    {
        this("JIP");
        System.out.println("Child class no-args constructor called");
    }
    public Child(String name)
    {
        super("JIP");
        System.out.println("Child class Parameterized constructor called by "+name);
    }
    public static void main(String args[])
    {
        Child c = new Child();
    }
}

Output :

Parent class Parameterized constructor called by JIP
Child class Parameterized constructor called by JIP
Child class no-args constructor called

6. Can we have this and super in the same constructor?

No, we cannot have have this and super in a same constructor as any one only can be in the first line of the constructor.

class Parent
{
    public Parent()
    {
        System.out.println("Parent class no-args constructor");
    }
}
public class Child extends Parent
{
    public Child()
    {
        this("JIP");
        super();
        System.out.println("Child class no-args constructor");
    }
    public Child(String name)
    {
        
        System.out.println("Child class Parameterized constructor"+name);
    }
    public static void main(String args[])
    {
        Child c = new Child();
    }
}

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Constructor call must be the first statement in a constructor

	at Child.(Child.java:13)
	at Child.main(Child.java:23)

7. Is it possible to call a sub class constructor from super class constructor?

No. You cannot call a sub class constructor from a super class constructor.

8. What is a No-arg constructor?

Constructor without arguments is called no-arg constructor. In Java Default constructor is a no-arg constructor.

class Demo
{
    public Demo()
    {
        //No-arg constructor
    }
}

9. Can we have a class with no Constructor in it ? What will happen during object creation ?

Yes, we can have a class with no constructor, When the compiler encounters a class with no constructor then it will automatically create a default constructor for you.

10. Can we have both Default Constructor and Parameterized Constructor in the same class?

Yes, we have both Default Constructor and Parameterized Constructor in the same class.

11. Can a Constructor return any value ?

A Constructor cannot return any explicit value but implicitly it will be returning the instance of the class.

12. Will compiler create the Default Constructor when we already have a Constructor defined in the class ?

No, the compiler will not create the Default Constructor when we already have a Constructor defined.

13. Can an abstract class in Java have a constructor?

Yes, an abstract class can have a constructor. The below code work perfectly fine.

abstract class Demo1 { 
    String value;
    public Demo1( String value ) {
        this.value = value;
    }
    public String getValue()
    {
    	return value;
    }
}
public class Test extends Demo1 {
    public Test() {
        super("CoreJava");
    }
}

14. What happens when a Constructor is defined as “protected” ?

In general protected method can be accessed by other class in a different package only through Inheritance. But when you assign protected access to a constructor it behaves a bit different. It can be accessed only by a call of super() (according to JLS) and not directly by any other means.

package com.javainterviewpoint;

public class Parent
{
    protected Parent()
    {
        System.out.println("Parent Constructor called");
    }
    public void parentDisp()
    {
        System.out.println("Parent Disp called");
    }
}
package com.javainterviewpoint1;

import com.javainterviewpoint.Parent;

public class Child extends Parent
{
    public Child()
    {
        /**
         * Using super() Parent Class protected constructor can be called
         */
        super(); 
        System.out.println("Child Constructor called");
    }
    public void childDisp()
    {
        System.out.println("Child Disp called");
    }
    public static void main(String args[])
    {
        /**
         * Even though we have extended Parent class in Child class, 
         * below way of calling Parent class Constructor is not allowed
         * 
         * The constructor Parent() is not visible - error will be thrown
         */
        Parent p = new Parent() // Error will be thrown
    }
}

15. Why constructors cannot be final in Java?

When you set a method as final, then” The method cannot be overridden by any class”, but Constructor by JLS ( Java Language Specification ) definition can’t be overridden. A constructor is not inherited, so there is no need for declaring it as final.

16. Why constructors cannot be abstract in Java?

When you set a method as abstract, then “The method doesn’t or cannot have body”. A constructor will be automatically called when object is created. It cannot lack a body moreover an abstract constructor could never be implemented.

17. Why constructors cannot be static in Java?

When you set a method as static, it means “The Method belong to class and not to any particular object” but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static.

Filed Under: Core Java, Java, Java Interview

Comments

  1. Siddhartha says

    February 4, 2018 at 8:37 am

    Thanks for your clean explination

    Reply
  2. Aarti says

    June 7, 2019 at 4:53 pm

    Thankyou so much

    Reply
  3. Pravallika says

    August 12, 2019 at 2:24 pm

    Thank you for providing material in detail

    Reply
  4. Somanath says

    September 12, 2019 at 11:48 am

    Nice and clear explaination. Thanks!

    Reply
  5. sumit bhardwaj says

    August 29, 2020 at 5:57 pm

    thanks for this…

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·