Q1: What is Object-Oriented Programming (OOP) in Java?
  • OOP is a programming paradigm that organizes software design around objects, which are instances of classes.
  • An object is an instance of a class, and a class serves as a blueprint defining properties (fields) and behaviors (methods).
  • It is based on four fundamental principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
  • OOP promotes code reusability, modularity, scalability, and easier maintenance.
  • Java fully supports OOP concepts, making it a widely used language for OOP-based software development.
  • Detail of OOPs
    Q2: What is encapsulation in Java?
    Data Hiding - Encapsulation

    Q3: Explain inheritance in Java with an example.
    Inheritance
    Q4: What is polymorphism in Java?
    Polymorphism
    Q5: What is abstraction, and how is it achieved in Java?
    Data Hiding - Abstraction
    Q6: Explain the difference between an abstract class and an interface.
    Feature Abstract Class Interface
    Definition A class that can have both abstract methods (without a body) and concrete methods (with a body). A blueprint that only contains abstract methods (until Java 8, after which default and static methods were introduced).
    Usage Used to represent a base class that provides partial implementation for subclasses. Used to define a contract that implementing classes must adhere to.
    Inheritance A class can extend only one abstract class (single inheritance). A class can implement multiple interfaces (multiple inheritance).
    Access Modifiers Abstract classes can have any access modifier for methods and fields (e.g., private, protected, public). All methods in an interface are public by default.
    Fields Can have instance variables and static variables. Fields are implicitly public, static, and final (constants).
    Constructor Can have a constructor to initialize fields. Cannot have a constructor.
    Example
    
              abstract class Animal {
                  abstract void makeSound();
                  void eat() {
                      System.out.println("Eating...");
                  }
              }
              
    
              interface Animal {
                  void makeSound();
                  default void eat() {
                      System.out.println("Eating...");
                  }
              }
              
    Note:

    Q7: How does Java implement multiple inheritance?

    Answer: Java implements multiple inheritance through interfaces.
    A class can implement multiple interfaces, thus inheriting behavior from all of them.
    This avoids the "diamond problem" caused by ambiguity in multiple inheritance.

    
          interface InterfaceA {
              void methodA();
          }
          
          interface InterfaceB {
              void methodB();
          }
          
          class MultiInheritanceClass implements InterfaceA, InterfaceB {
              public void methodA() {
                  System.out.println("Method A from InterfaceA");
              }
          
              public void methodB() {
                  System.out.println("Method B from InterfaceB");
              }
          }
          
          public class Test {
              public static void main(String[] args) {
                  MultiInheritanceClass obj = new MultiInheritanceClass();
                  obj.methodA();
                  obj.methodB();
              }
          }
            
    Q8: Can a class be declared as both `abstract` and `final`?

    Answer: No, a class cannot be both abstract and final because an abstract class is meant to be extended, whereas a final class cannot be extended.

    Q9: What is a constructor, and what are its types?

    Answer: A constructor is a special method used to initialize objects. Types:

    Q10: What is the role of the `super` keyword in Java?

    Answer: The super keyword is used to refer to the immediate parent class. It can be used to call the parent class constructor or methods.

    class Animal {
          void eat() {
              System.out.println("Animal eats.");
          }
      }
      
      class Dog extends Animal {
          void eat() {
              super.eat();
              System.out.println("Dog eats.");
          }
      }
      
    Q11: Explain the concept of method overloading and method overriding.

    Method Overloading: This occurs when multiple methods in the same class share the same name but have different parameter lists (number, type, or order of parameters). It is a compile-time polymorphism.

    Key Points:

    
          class Calculator {
              // Overloaded methods
              int add(int a, int b) {
                  return a + b;
              }
          
              double add(double a, double b) {
                  return a + b;
              }
          
              int add(int a, int b, int c) {
                  return a + b + c;
              }
          }
          
          public class OverloadingExample {
              public static void main(String[] args) {
                  Calculator calc = new Calculator();
                  System.out.println(calc.add(2, 3));        // Calls int add(int, int)
                  System.out.println(calc.add(2.5, 3.5));   // Calls double add(double, double)
                  System.out.println(calc.add(1, 2, 3));    // Calls int add(int, int, int)
              }
          }
            

    Method Overriding: This occurs when a subclass provides a specific implementation for a method already defined in its parent class. It is runtime polymorphism.

    Key Points:

    
          class Parent {
              void display() {
                  System.out.println("Display from Parent");
              }
          }
          
          class Child extends Parent {
              @Override
              void display() {
                  System.out.println("Display from Child");
              }
          }
          
          public class OverridingExample {
              public static void main(String[] args) {
                  Parent obj = new Child(); // Upcasting
                  obj.display(); // Calls Child's overridden method
              }
          }
            

    Tricky Points:

    Q12: Can you override a static method in Java?

    No, static methods cannot be overridden in Java. Instead, if a static method is defined in both the parent and child classes with the same name and parameters, it is known as method hiding. The method called depends on the reference type, not the object type.

    
          class Parent {
              static void staticMethod() {
                  System.out.println("Static method in Parent");
              }
          }
          
          class Child extends Parent {
              static void staticMethod() {
                  System.out.println("Static method in Child");
              }
          }
          
          public class StaticMethodTest {
              public static void main(String[] args) {
                  Parent parent = new Parent();
                  Parent childAsParent = new Child();
                  Child child = new Child();
                  
                  parent.staticMethod();           // Outputs: Static method in Parent
                  childAsParent.staticMethod();    // Outputs: Static method in Parent (method hiding)
                  child.staticMethod();            // Outputs: Static method in Child
              }
          }
            

    Key Points:

    Q13: What is an inner class, and why is it used?

    Answer: An inner class in Java is a class that is defined within another class. Inner classes are used to logically group classes that are only used in one place, improve encapsulation, and make the code more readable and maintainable.

    Types of Inner Classes:

    Example: Member Inner Class

    
          class OuterClass {
              private String message = "Hello from Outer Class!";
              
              class InnerClass {
                  void displayMessage() {
                      System.out.println(message); // Accessing private member of the outer class
                  }
              }
          }
          
          public class InnerClassExample {
              public static void main(String[] args) {
                  OuterClass outer = new OuterClass();
                  OuterClass.InnerClass inner = outer.new InnerClass();
                  inner.displayMessage();
              }
          }
            

    Why Use Inner Classes?

    Q14: What is the difference between `this` and `super` keywords?

    Answer:

    Q15: How do you achieve immutability in Java?

    Answer: Create a class with:

    final class Immutable {
          private final String name;
      
          Immutable(String name) {
              this.name = name;
          }
      
          public String getName() {
              return name;
          }
      }
      
    Q16: What is a sealed class in Java?

    Answer: A sealed class in Java restricts the inheritance of the class to a specific set of classes. It is a way to restrict the subclassing of a class, ensuring that only a designated set of classes can inherit it. Sealed classes are introduced in Java 16.

    Key Features:

    Example:

    
          sealed class Shape permits Circle, Rectangle {
              double area;
          
              Shape(double area) {
                  this.area = area;
              }
          
              abstract double calculateArea();
          }
          
          final class Circle extends Shape {
              Circle(double area) {
                  super(area);
              }
          
              @Override
              double calculateArea() {
                  return Math.PI * area * area;
              }
          }
          
          final class Rectangle extends Shape {
              double length, width;
          
              Rectangle(double area, double length, double width) {
                  super(area);
                  this.length = length;
                  this.width = width;
              }
          
              @Override
              double calculateArea() {
                  return length * width;
              }
          }
          
          public class SealedClassExample {
              public static void main(String[] args) {
                  Shape circle = new Circle(10.0);
                  Shape rectangle = new Rectangle(20.0, 5.0, 4.0);
                  
                  System.out.println("Circle Area: " + circle.calculateArea());
                  System.out.println("Rectangle Area: " + rectangle.calculateArea());
              }
          }
            

    Why Use Sealed Classes?

    Q17: What is the Liskov Substitution Principle?

    Answer: It states that objects of a superclass should be replaceable with objects of its subclasses without affecting the functionality of the program.

    Q18: Can an interface extend another interface?

    Answer: Yes, an interface can extend another interface. This allows a child interface to inherit methods from the parent interface.

    Q19: What is the `instanceof` keyword?

    Answer: The instanceof keyword is used to test whether an object is an instance of a specific class or subclass.

    Q20: What is the purpose of the `default` methods in interfaces?

    Answer: Default methods, introduced in Java 8, allow adding new methods to interfaces without breaking existing implementations.

    Q21: Explain the use of functional interfaces in Java 8.

    Answer: A functional interface is an interface with a single abstract method. It is used in lambda expressions and method references. Example: Runnable, Predicate.

    Q22: How does Java handle object cloning?

    Answer: Java provides cloning using the clone() method of the Object class. A class must implement Cloneable to use it.

    Q23: What is composition in OOP?

    Answer: Composition is a design principle where a class contains objects of other classes to achieve reusability.

    Q24: Explain dependency injection.

    Answer: Dependency Injection is a design pattern where objects are provided their dependencies instead of creating them internally, promoting loose coupling.

    Q25: What are default constructors?

    Answer: A default constructor is provided by Java if no constructor is explicitly defined. It initializes objects with default values.

    Q26: Can you explain the concept of method hiding?

    Answer: Method hiding occurs when a static method in a subclass has the same name and signature as one in its superclass. The method is hidden, not overridden.

    Q27: What are the SOLID principles?

    Answer: SOLID principles are design principles for maintainable software:

    Q28: What is the difference between aggregation and composition?

    Answer:

    Q29: What is the Open/Closed Principle?

    Answer: This principle states that a class should be open for extension but closed for modification.

    Q30: How do you ensure a class follows the Single Responsibility Principle?

    Answer: A class should only have one reason to change. You can achieve this by keeping related functionalities together and separating unrelated functionalities into different classes.