Java Constructors

Last Updated :
Discuss
Comments

Question 1

Which of the following is true about Java constructors?

  • Constructors have a return type of void.

  • Constructors must always be public.

  • A constructor is automatically called when an object is created.

  • Constructors can only be defined explicitly.


Question 2

What happens if you do not define a constructor in a Java class?

  • The program will not compile.

  • The compiler provides a default constructor.

  • The class cannot be instantiated.

  • The constructor from another class will be used.


Question 3

Can a Java constructor be private?


  • No, it must be public.

  • Yes, but the class cannot be instantiated outside the class.

  • Yes, and it can be accessed from anywhere.

  • No, Java does not allow private constructors.

Question 4

How can one constructor call another constructor within the same class?

  • Using super()

  • Using this()

  • Using new()

  • Constructors cannot call each other


Question 5

What will be the output of this program?

Java
class Demo {
    int num;
    Demo() {
        this(100);
        System.out.println("Default Constructor");
    }
    Demo(int n) {
        num = n;
        System.out.println("Parameterized Constructor");
    }
}
public class Main {
    public static void main(String[] args) {
        Demo obj = new Demo();
    }
}


  • Default Constructor

  • Parameterized Constructor

  • Parameterized Constructor
    Default Constructor

  • Compilation Error


Question 6

Can a constructor be final in Java?


  • Yes, if you override it.

  • No, because constructors are not inherited.

  • Yes, but only in abstract classes.

  • Yes, but only for utility classes.

Question 7

What will be the output of the following code?

Java
class Base {
    Base() {
        System.out.println("Base Constructor");
    }
}
class Derived extends Base {
    Derived() {
        System.out.println("Derived Constructor");
    }
}
public class Main {
    public static void main(String[] args) {
        Derived obj = new Derived();
    }
}


  • Base Constructor
    Derived Constructor

  • Derived Constructor
    Base Constructor


  • Compilation Error

  • Runtime Error

Question 8

What will be the output of this program?

Java
class A {
    private A() {
        System.out.println("Private Constructor");
    }
    public static void createInstance() {
        new A();
    }
}
public class Main {
    public static void main(String[] args) {
        A.createInstance();
    }
}


  • Compilation Error

  • Private Constructor

  • Runtime Error


  • No Output

Question 9

What is the purpose of a constructor?


  • Destroy objects

  • Allocate memory

  • Initialize objects

  • Call main() method

There are 9 questions to complete.

Take a part in the ongoing discussion