0
0
Javaprogramming~20 mins

Default constructor in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Default Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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);
    }
}
ACompilation error
Bnull
C0
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Think about what Java does if you don't write any constructor.
🧠 Conceptual
intermediate
2:00remaining
Role of default constructor in inheritance
Consider these classes: class Parent {} class Child extends Parent {} What happens when you create new Child()?
ARuntime error due to missing constructor
BChild's default constructor does not call Parent's constructor
CCompilation error because Parent has no constructor
DChild's default constructor calls Parent's default constructor automatically
Attempts:
2 left
πŸ’‘ Hint
Think about how constructors work in inheritance when none are defined.
❓ Predict Output
advanced
2: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);
    }
}
A10
B0
CCompilation error
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Look at the constructor and what it does to the value field.
❓ Predict Output
advanced
2: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?
ACompilation error: constructor A() is undefined
BRuntime error
CCompiles and runs fine
DCompilation error: constructor B() is undefined
Attempts:
2 left
πŸ’‘ Hint
Think about what happens if superclass has no default constructor.
🧠 Conceptual
expert
2:00remaining
How many constructors are created by default?
If you write a Java class with no constructors, how many constructors does the compiler create?
ANo constructors are created automatically
BOne default constructor with no parameters
COne constructor with parameters matching all fields
DTwo constructors: one default and one copy constructor
Attempts:
2 left
πŸ’‘ Hint
Think about what Java provides if you don't write any constructor.