Govt Exams
class Parent { void display() { System.out.println("Parent"); } }
class Child extends Parent { void display() { System.out.println("Child"); } }
public class Test { public static void main(String[] args) { Parent p = new Child(); p.display(); } }
This demonstrates runtime polymorphism. Even though p is a Parent reference, it points to a Child object, so the overridden display() method in Child class is executed.
'protected' members are accessible within the same package and also to subclasses in different packages. It provides more access than default but less than public.
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.
In Java, a class implements an interface. A class extends another class. An interface can extend another interface. This is the correct terminology and relationship structure.
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 8 introduced default and static methods in interfaces. Any class implementing an interface must provide implementations for all its abstract methods (unless the implementing class is abstract).
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.
Method overloading requires methods to have the same name but different parameter lists (different types, number, or order of parameters). Return type alone cannot distinguish overloaded methods.
Abstract classes cannot be instantiated but can contain both abstract methods (without implementation) and concrete methods (with implementation). This allows providing default behavior while enforcing certain methods to be implemented by subclasses.