What is a constructor in Java?
A
A method that returns a value
B
A special method used to initialize objects
C
A static method that runs once
D
A method with a return type of void
Analysis & Theory
A constructor is a special method called when an object is created, used to initialize the object.
Which of the following is true about constructors?
A
They must have a return type
C
They must have the same name as the class
D
They can be private only
Analysis & Theory
Constructors must have the same name as the class and cannot have a return type.
What is the output?
```java
class Car {
Car() {
System.out.println("Car Created");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
}
}```
Analysis & Theory
The constructor is called when `new Car()` is executed, printing 'Car Created'.
Can a class have multiple constructors?
B
Yes, using constructor overloading
C
Only if they are private
Analysis & Theory
Java supports constructor overloading, allowing multiple constructors with different parameters.
What happens if no constructor is defined in a Java class?
B
Java provides a default constructor automatically
C
The class cannot be instantiated
D
It becomes an abstract class
Analysis & Theory
Java provides a no-argument default constructor if none is defined.
What is the output?
```java
class A {
A(int x) {
System.out.println(x);
}
}
public class Main {
public static void main(String[] args) {
A a = new A(10);
}
}```
Analysis & Theory
The parameterized constructor is called with value 10 and prints it.
Which keyword is used to call one constructor from another in the same class?
Analysis & Theory
`this()` is used to call another constructor from the same class.
What is constructor overloading?
A
Having two classes with the same name
B
Having multiple constructors with different parameter lists
C
Overriding constructors in subclass
D
Using static constructors
Analysis & Theory
Constructor overloading allows multiple constructors with different parameter types or numbers.
Can constructors be `private` in Java?
A
No, constructors must always be public
B
Yes, useful for Singleton pattern or factory methods
C
Only in abstract classes
D
Only if the class is static
Analysis & Theory
Private constructors are allowed and are used to restrict object creation, e.g., Singleton pattern.
What is the output?
```java
class Person {
String name;
Person(String n) {
name = n;
}
void greet() {
System.out.println("Hi " + name);
}
}
class Main {
public static void main(String[] args) {
Person p = new Person("Alice");
p.greet();
}
}```
Analysis & Theory
The constructor sets the name to 'Alice' and greet() prints it.