Govt. Exams
Entrance Exams
The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application. Option B correctly represents this principle.
Deep inheritance hierarchies are considered a code smell. They suggest that composition might have been a better approach, leading to tighter coupling and reduced flexibility.
interface I1 { default void show() { System.out.println("I1"); } }
interface I2 { default void show() { System.out.println("I2"); } }
class C implements I1, I2 { public void show() { I1.super.show(); } public static void main(String[] args) { new C().show(); } }
When a class implements multiple interfaces with the same default method, it must explicitly override the method. Using I1.super.show() calls I1's default implementation.
Liskov Substitution Principle: A child class method can throw the same exception or a narrower exception than the parent method, not a broader one.
Abstract classes are suitable when you have shared state and constructors needed. An Account has properties like balance and account number, making abstract class the better choice.
class A { static void display() { System.out.println("A"); } }
class B extends A { static void display() { System.out.println("B"); } }
public class Test { public static void main(String[] args) { A ref = new B(); ref.display(); } }
Static methods are resolved at compile-time based on the reference type, not the object type. Hence, A.display() is called, not B.display(). This is method hiding, not overriding.
Method overloading is compile-time (static) polymorphism with same method name but different parameters in the same class. Method overriding is runtime (dynamic) polymorphism where a child class provides a specific implementation of a parent method.
Abstract classes cannot be directly instantiated, but you can create objects using anonymous inner classes that implement the abstract methods.
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); } }
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.
When unrelated classes need to implement a common contract, an interface is the best choice. Interfaces are specifically designed for this purpose, allowing multiple implementation without forcing an inheritance hierarchy.