Govt. Exams
Entrance Exams
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.
Static methods belong to the class, not instances. When called on an instance, Java internally calls the method on the class. Static methods cannot access instance variables or use 'this' keyword.
To prevent inheritance, use 'final' on the class. To make instances immutable, declare all fields as 'final' and ensure they are not modified after initialization. A classic example is the String class.
Java automatically inserts a call to the parent class's no-arg constructor if 'super()' is not explicitly called. This ensures parent class initialization happens before child class initialization.
interface I1 {
void method1();
}
interface I2 extends I1 {
void method2();
}
class C implements I2 {
public void method1() { System.out.println("M1"); }
public void method2() { System.out.println("M2"); }
}
public class Test {
public static void main(String[] args) {
I1 obj = new C();
obj.method2();
}
}
obj is of type I1 which doesn't have method2(). Though actual object C has method2(), reference type determines what methods are accessible.
class Test {
int x = 5;
{
x = 10;
}
Test() {
x = 15;
}
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
}
}
Instance initializer block executes after variable initialization but before constructor. Constructor executes last, setting x = 15.
interface A {
void show();
}
class B implements A {
public void show() {
System.out.println("B");
}
}
class C extends B {
public void show() {
System.out.println("C");
}
}
A obj = new C();
obj.show();
Polymorphism in action. obj is of type A (interface), but actual object is C. C's show() method is called, printing 'C'.