Govt Exams
The Factory Pattern uses a separate class (factory) with methods to create and return objects. This decouples object creation from usage.
This demonstrates dynamic (runtime) polymorphism. The actual object type (ElectricCar) determines which method is called, not the reference type (Vehicle).
Java 17 introduced 'sealed' classes with the 'permits' clause to explicitly specify which classes can extend a sealed class, providing better control over inheritance.
An abstract class allows you to define both abstract methods (to be overridden) and concrete methods (shared implementation), which is ideal for this scenario.
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.
The 'final' keyword prevents a class from being extended. 'sealed' (Java 17+) allows selective subclassing, but 'final' is the standard way to prevent all subclassing.