Govt Exams
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.
Composition (HAS-A relationship) is often preferred over inheritance (IS-A relationship) because it's more flexible and avoids tight coupling.
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.
Default methods in interfaces (Java 8+) provide a default implementation. Implementing classes can use this default implementation or override it as needed.
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.
From Java 8, interfaces can have default and static methods, but abstract classes can have instance variables, constructors, and private methods which interfaces cannot have.
If a parent class has a parameterized constructor and no default constructor, the child class must explicitly call it using super() to initialize parent class members.
'this' is a reference to the current object instance, while 'super' is a reference to the parent class. They serve different purposes in inheritance hierarchy.
The 'final' keyword when applied to a variable makes it a constant. When applied to a class, it cannot be extended. When applied to a method, it cannot be overridden.