Challenge - 5 Problems
Default Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of a class with no explicit constructor
What is the output of this Java program?
Java
public class Test { int x; public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.x); } }
Attempts:
2 left
π‘ Hint
Think about what Java does if you don't write any constructor.
β Incorrect
Java provides a default constructor that initializes int fields to 0.
π§ Conceptual
intermediate2:00remaining
Role of default constructor in inheritance
Consider these classes:
class Parent {}
class Child extends Parent {}
What happens when you create new Child()?
Attempts:
2 left
π‘ Hint
Think about how constructors work in inheritance when none are defined.
β Incorrect
If no constructor is defined, Java inserts a default constructor that calls super().
β Predict Output
advanced2:00remaining
Output when default constructor is overridden
What is the output of this code?
Java
public class Demo { int value; Demo() { value = 10; } public static void main(String[] args) { Demo d = new Demo(); System.out.println(d.value); } }
Attempts:
2 left
π‘ Hint
Look at the constructor and what it does to the value field.
β Incorrect
The constructor sets value to 10, so the output is 10.
β Predict Output
advanced2:00remaining
What error occurs without default constructor in subclass?
Given these classes:
class A {
A(int x) {}
}
class B extends A {
B() {}
}
What happens when compiling?
Attempts:
2 left
π‘ Hint
Think about what happens if superclass has no default constructor.
β Incorrect
Subclass constructor must call superclass constructor explicitly if no default exists.
π§ Conceptual
expert2:00remaining
How many constructors are created by default?
If you write a Java class with no constructors, how many constructors does the compiler create?
Attempts:
2 left
π‘ Hint
Think about what Java provides if you don't write any constructor.
β Incorrect
Java automatically creates one no-argument default constructor if none is defined.