Govt Exams
The @Override annotation helps verify that you are correctly overriding a parent method and improves code clarity, but it does NOT automatically invoke the parent class method. You must use super.methodName() for that. @Override is purely a compile-time marker for verification purposes.
Multiple inheritance of implementation can cause the diamond problem. Java avoids this by allowing single class inheritance but multiple interface implementation.
'this' cannot be used in static methods because static methods are class-level and don't have an instance context. 'this' always refers to an instance.
class A { int x = 5; }
class B extends A { int x = 10; }
public class Test {
public static void main(String[] args) {
A a = new B();
System.out.println(a.x);
}
}
Variable shadowing occurs here. 'a' is of type A, so a.x refers to A's variable x which is 5. Variables are not overridden, only methods are.
The interface provides abstraction by hiding implementation details. Multiple classes implementing the same interface method demonstrates polymorphism (many forms).
This is method overloading, not overriding, because the method signature is different (different parameters). Overriding requires the same signature.
class Test {
static int x = 10;
public static void main(String[] args) {
System.out.println(x++);
}
}
The post-increment operator (x++) returns the value before incrementing. So it prints 10, and then x becomes 11.
Through inheritance, a Puppy reference can access all non-private methods from Puppy, Dog, and Animal classes through the inheritance chain.
Interfaces cannot be instantiated directly. Since Java 8, interfaces can have static and default methods, and since Java 9, they can have private methods.
The super() keyword is used to call the parent class constructor. It must be the first statement in the child class constructor.