What is the output of this code?
class A { int x = 10; }
class B extends A { int x = 20; }
public class Test { public static void main(String[] args) { A a = new B(); System.out.println(a.x); } }
A10
B20
CCompilation Error
DRuntime Error
Correct Answer:
A. 10
EXPLANATION
Variable shadowing occurs here. The reference type is A, so a.x accesses A's x field which is 10. Method overriding works with methods, not instance variables.
Which of the following is true about abstract classes?
AThey can have constructors
BThey cannot have any concrete methods
CThey must be instantiated directly
DThey can only have abstract methods
Correct Answer:
A. They can have constructors
EXPLANATION
Abstract classes can have constructors to initialize instance variables. They can contain both abstract and concrete methods, and they cannot be directly instantiated.
ADefining multiple methods with different parameters but same name
BDefining multiple methods with same parameters and same name
CCreating methods in parent and child classes with same name
DCalling a method multiple times
Correct Answer:
A. Defining multiple methods with different parameters but same name
EXPLANATION
Method overloading allows multiple methods with the same name but different parameters (number, type, or order). It is a compile-time (static) polymorphism.
Consider:
interface I1 { void method(); }
interface I2 { void method(); }
class C implements I1, I2 { public void method() { System.out.println("Method"); } }
What will be the behavior?
ACompilation error due to ambiguity
BThe single method implementation satisfies both interfaces
CRuntime error
DOnly I1's method is implemented
Correct Answer:
B. The single method implementation satisfies both interfaces
EXPLANATION
When a class implements multiple interfaces with the same method signature, a single method implementation satisfies all interfaces. This is resolved at compile time.
Correct Answer:
B. It refers to the current instance of the class
EXPLANATION
'this' is a reference variable that refers to the current object instance. It is commonly used to distinguish instance variables from parameters with the same name.
Consider the code:
class A { A() { System.out.println("A"); } }
class B extends A { B() { super(); System.out.println("B"); } }
What will be printed when 'new B()' is executed?
AB then A
BA then B
COnly B
DCompilation Error
Correct Answer:
B. A then B
EXPLANATION
The super() call invokes the parent class constructor first, printing 'A', then the child constructor completes, printing 'B'.