Java Constructors (original) (raw)
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.
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.
What will be the output of the following Java code?
Java `
class Test { int x; Test() { x = 10; } } public class Main { public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.x); } }
`
Can a Java constructor be private?
- 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.
How can one constructor call another constructor within the same class?
- Constructors cannot call each other
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(); } }
`
- Parameterized Constructor
- Parameterized Constructor
Default Constructor
What will happen if you explicitly define a constructor with parameters but do not define a no-argument constructor?
- Java will provide a default no-argument constructor.
- You cannot create an object without passing arguments.
- Compilation error occurs.
- The constructor will be inherited from Object class.
Can a constructor be final in Java?
- No, because constructors are not inherited.
- Yes, but only in abstract classes.
- Yes, but only for utility classes.
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
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(); } }
`
There are 10 questions to complete.
Take a part in the ongoing discussion