Inheritance, Polymorphism, Exceptions & Collections
Advanced Java | Undergraduate CS
Questions & Verified Answers
, Java OOP Advanced — Inheritance, Polymorphism &
Collections
25 questions covering advanced Java: inheritance, polymorphism, abstract classes, interfaces,
exception handling, and ArrayList operations.
Q1. How can you prevent a class from being instantiated in Java?
A. No modifiers on the constructor
B. Use private on the constructor
C. Use static on the constructor
D. Use public on the constructor
Answer: B. Use the private modifier on the constructor.
A private constructor prevents new ClassName() from being called outside the class.
Commonly used in: Singleton pattern, utility classes with only static methods.
Note: static constructors are not allowed in Java — option C is invalid syntax.
Q2. Analyze: class TempClass { int i; public void TempClass(int j){i=j;} } — new TempClass(2).
What happens?
A. Runs fine
B. Runtime error
C. Compile error
D. Works but i is 0
Answer: C. Compile error — TempClass does not have a constructor with an int argument.
'public void TempClass(int j)' has a return type (void) → it is a METHOD, not a constructor.
A constructor has NO return type. Since no constructor is defined, Java provides only a no-arg
default.
Fix: remove 'void': public TempClass(int j) { i = j; }
Q3. What is the output when new B() is called, given: class A has a constructor that calls setI(20)
and prints 'i from A is '+i, and class B overrides setI to set i = 3*i?
A. i from A is 7
B. i from A is 60
C. i from A is 20
D. i from A is 0
Answer: B. i from A is 60
When new B() runs, A's constructor is called first.
Inside A's constructor, setI(20) is called. Due to polymorphism, B's overridden setI runs.
B's setI: i = 3 × 20 = 60. Then A's constructor prints: i from A is 60.
Key lesson: overridden methods are called polymorphically even inside superclass constructors.
Q4. When does polymorphism (dynamic binding) NOT apply in Java?
A. Overridden instance methods
B. Static methods
C. Abstract methods
D. Interface methods