0% found this document useful (0 votes)
18 views49 pages

OOPS Interview Questions

The document is a comprehensive guide on Object-Oriented Programming (OOP) interview questions, covering 140 questions across various stages including OOP fundamentals, encapsulation, inheritance, polymorphism, and abstraction. It provides practical answers and explanations for key concepts such as classes, objects, constructors, encapsulation, and inheritance, along with examples and comparisons. The content is structured in stages, making it easy to navigate through different OOP topics.

Uploaded by

yepox29888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views49 pages

OOPS Interview Questions

The document is a comprehensive guide on Object-Oriented Programming (OOP) interview questions, covering 140 questions across various stages including OOP fundamentals, encapsulation, inheritance, polymorphism, and abstraction. It provides practical answers and explanations for key concepts such as classes, objects, constructors, encapsulation, and inheritance, along with examples and comparisons. The content is structured in stages, making it easy to navigate through different OOP topics.

Uploaded by

yepox29888
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

OOPS Interview Questions

(140 Questions with Practical Answers)

🟩 STAGE 1: OOP Fundamentals


🟨 STAGE 2: Encapsulation
🟧 STAGE 3: Inheritance
🟦 STAGE 4: Polymorphism
🟪 STAGE 5: Abstraction
⬛ STAGE 6: Object Relationships
🟫 STAGE 7: Important OOP Keywords
🟧 STAGE 8: Comparison-Based Topics

l
ha
hc
STAGE 1: OOP Fundamentals

A. Class & Object Basics


is
1. What is a class in Java?​
N
Answer : A class is a blueprint or template for creating objects. It defines state and
behavior (methods) of objects. Think of it as a cookie cutter, while objects are the cookies.
ith
eW

2. What is an object in Java?​


od

Answer: An object is a real-world instance of a class. It has its own state stored in memory
and can use the class’s methods to perform behavior.
C

3. How do you create an object in Java?​


Ans: Objects are created using the new keyword, which allocates memory & calls the
constructor.

Car car1 = new Car(); // Object created

Car car2 = new Car(); // Another object


4. What is the difference between a class and an object?

Class Object

Blueprint or template Instance of a class

Defines state and behavior Holds actual values for state

Exists in code Exists in memory (heap)

Can’t perform action by itself Can perform actions using methods

l
Example: Car is the class, myCar is the object.

ha
5. What is the purpose of the new keyword in Java?​
Answer:

hc
●​ Allocates memory on the heap for a new object.
●​ Calls the constructor to initialize the object.

Car car = new Car(); // 'new' allocates memory and calls constructor
is
N
6. What happens in memory when an object is created?​
Answer:
ith

1.​ Memory allocated on heap for instance variables.


2.​ The constructor initializes variables.
3.​ The reference variable points to the memory location in the stack.
eW

Stack: car -> Heap: Car object {brand: null, speed: 0}


od

7. Can you have a class without any attributes or methods?​


Answer: Yes, Java allows empty classes. Sometimes used as marker classes.

class Marker {}
C

8. What are instance variables and instance methods?​


Answer:

Instance Variables

●​ Definition: Variables that belong to an instance (object) of a class.


●​ Scope: Each object of the class has its own copy of instance variables.
●​ Declaration: Declared inside the class but outside any method, usually without
static.
●​ Access: Accessed through the object reference.
If you create two objects:

Car car1 = new Car();

Car car2 = new Car();

car1.color = "Red";

l
ha
car2.color = "Blue";

●​ car1.color is "Red" and car2.color is "Blue" → each object has its own copy.

hc
Instance Methods

●​ Definition: Methods that belong to an instance (object) of a class.


●​
●​
is
Access: Can access instance variables and other instance methods directly.
Declaration: Normal methods without the static keyword.
●​ Example:
N
ith
eW
od

9. What is a static variable and how is it different from an instance variable?​


Answer:
C

●​ Static variable: A static variable (also called a class variable) is a variable that
belongs to the class rather than to any specific object. It is declared using the static
keyword. All objects of the class share the same copy of a static variable. It is mainly
used to store common properties or values that are shared among all instances of
the class.
Difference Between Static and Instance Variables

Feature Instance Variable Static Variable

Belongs to Object (each object has its own copy) Class (shared by all objects)

Memory Allocated when object is created Allocated only once when class is
Allocation loaded

l
ha
Access Through object reference Through class name (or object)

hc
Purpose Store object-specific data Store class-level/shared data

is
10. Can static methods access instance variables? Why or why not?​
Answer:​
N
No, static methods belong to the class, not any object. They cannot access instance
variables directly because instance variables belong to objects.
ith
eW
od
C
B. Constructors & Initialization

11. What is a constructor in Java?​


Answer: A constructor is a special block of code used to initialize objects.

●​ It has no return type (not even void).


●​ The name must match the class name.

l
ha
hc
is
Tip: Always mention constructors are implicitly called when new is used.
N
12. What is the difference between a constructor and a method?

Constructor Method
ith

No return type Has return type (even void)


eW

Name = Class name Name = any valid identifier

Called automatically when object is Called explicitly


created

Used to initialize object Used to perform operations


od

13: What are the types of constructors in Java?


C

1.​ Default Constructor (No-Arg Constructor)


○​ Definition: A constructor that takes no arguments.
○​ Purpose: Initializes objects with default values.
2. Parameterized Constructor

●​ Definition: A constructor that accepts arguments to initialize an object with specific


values.
●​ Purpose: Provides flexibility to create objects with different states.

l
ha
3. Copy Constructor (Optional in Java, user-defined)

●​ Definition: A constructor that creates a new object by copying values from

hc
another object.
●​ Purpose: To duplicate an existing object.

is
N
ith

14. What is a default constructor? When is it created by the compiler?​


eW

Answer:

●​ A default constructor is a no-argument constructor automatically provided by the


compiler if no constructors are defined.
●​ If you define any constructor, the compiler does not create a default one.
od

class Car { } // compiler adds: Car() {}


15. Can a constructor be private? If yes, where is it useful?​
Answer: Yes — private constructors are used for:
C

●​ Singleton design pattern


●​ Static utility classes (like Math)​
16. Can a class have multiple constructors? How?​
Answer: Yes — constructor overloading allows multiple constructors with different
parameters.

l
ha
hc
is
N
17. Can constructors be overloaded?​
Answer: Yes — just like methods, constructors can have different parameter lists.
ith

●​ Overloading allows creating objects in different ways.​


eW
od

18. What happens if you define a parameterized constructor but not a default one?​
Answer:
C

●​ Compiler does not provide a default constructor.


●​ Trying to create an object with no arguments will cause a compile-time error.​
19. Can a constructor call another constructor? How?​
Answer: Yes — use this() to call another constructor in the same class.

●​ Must be the first statement in the constructor.

l
ha
hc
is
20. What is constructor chaining?​
Answer: Constructor chaining = calling one constructor from another (either within the
N
same class using this() or from the parent class using super()).

●​ Helps avoid code duplication and initialize objects efficiently.


ith
eW
od
C

21. Can we inherit constructors from the parent class?​


Answer:

●​ No, constructors are not inherited.


●​ A subclass can call a parent constructor using super(), but cannot directly inherit it.​

C. Static, this Keyword, Instance vs Class Variables, Getters & Setters

22. What is this keyword in Java?​


Answer :

●​ this refers to the current object.


●​ Used to differentiate instance variables from parameters, call other constructors, or
pass the current object.

l
ha
hc
is
23. What is a static variable in Java?​
N
Answer:

●​ Belongs to the class, not individual objects.


ith

●​ Shared by all instances of the class.


●​ Stored in method area (class memory), not heap.​
eW
od
C

24. What is a static method in Java?​


Answer: It belongs to class, can be called without creating an object & can access only
static variables/methods. It cannot use this because no instance is associated.
25. Difference between instance variables and static variables?

Instance Variable Static Variable

Belongs to object Belongs to class

Unique per object Shared across all


objects

Stored in heap Stored in method area

Accessed via object Accessed via class


reference name

l
ha
26. What are getters and setters? Why do we use them?​
Answer :

hc
●​ Methods used to access and modify private variables (encapsulation).
●​ Useful for validation and controlling access.
is
N
ith
eW

27. Can a static method access instance variables?​


od

Answer:

●​ ❌ No, because instance variables belong to objects, and static methods belong to
the class.
C

●​ To access instance variables, pass an object reference.​


28. Can this be used in a static method?​
Answer:

●​ ❌ No, this refers to the current object, but static methods don’t belong to any object.

l
29. What happens if you don’t use getters/setters and make variables public?​

ha
Answer:

●​ Encapsulation is broken → anyone can modify directly → no validation/control →


higher chance of bugs.

hc
●​ Using getters/setters makes your class maintainable and secure.

30. Can static variables and methods be accessed via objects?​


Answer:

●​
is
✅ Yes, but not recommended — should access via class name to indicate
N
shared nature.
ith
eW
od
C
STAGE 2: Encapsulation

A. Core Concept

31. What is encapsulation in Java?​


Answer : Encapsulation is the mechanism of wrapping data (variables) and behavior
(methods) together and restricting direct access to some components.

●​ Ensures controlled access to the object's state.

l
ha
hc
32. Why is encapsulation important in OOP?
is
●​ Protects object state from unintended modifications.
●​ Makes code more maintainable and flexible.
N
●​ Supports modular programming and team collaboration.\

33. How does encapsulation differ from abstraction?


ith

●​ Encapsulation: Hides implementation details at the object level using access


modifiers.
eW

●​ Abstraction: Hides complexity at class/method level, showing only what an object


can do.

34. What is data hiding and how does Java achieve it?

Answers: Data hiding is a key part of encapsulation — it prevents outside classes from
od

accessing the internal state directly. In Java, we achieve this using private access modifiers
on variables and public getters/setters to provide controlled access.
C

●​ Data hiding is restricting access to object state.


●​ Achieved using private variables + public getters/setters.
35. What are the key features that enable encapsulation in Java?

●​ Private variables: Restrict direct access.


●​ Public/protected getters and setters: Controlled access.
●​ Final keyword: Helps create immutable fields.
●​ Access modifiers: Determine visibility (public, private, protected, default).

36. Can encapsulation exist without access modifiers?

Answer: Not fully. While methods and variables are package-private by default, true
encapsulation requires control over visibility, which is only possible with access modifiers like
private or protected. Without them, other classes in the same package can modify variables
directly, breaking encapsulation.

l
ha
37. Is encapsulation only about making variables private?

Ans: No. While making variables private is a key part, encapsulation also involves:

hc
●​ Providing controlled access through methods
●​ Possibly making fields immutable for better control
is
38. How does encapsulation improve code maintainability and flexibility?

Ans: Encapsulation allows you to change internal implementation without affecting code that
N
uses the class. For example:
ith
eW
od

39. What will happen if we make instance variables public?

Ans: If variables are public, any class can modify them directly. This can:
C

●​ Cause invalid states


●​ Break object integrity
●​ Lead to tightly coupled code

40. What are the disadvantages of not using encapsulation?

●​ Increased risk of invalid data


●​ Harder to maintain and refactor code
●​ Poor modularity and reusability
●​ Makes team collaboration more error-prone
B. Practical Implementation

41. What are getters and setters in Java?

●​ Getters: Methods that return the value of private variables.


●​ Setters: Methods that modify the value of private variables.
●​ Enable controlled access to fields.

42. Why do we use getters and setters instead of accessing variables directly?

●​ To validate input before setting values.

l
●​ To encapsulate data, hiding implementation.

ha
●​ To allow future changes without affecting external code.

43. Can we have only a getter or only a setter in a class? Why?

✅ Yes.

hc
Ans:

Getter-only → Read-only property (e.g., ID).​


Setter-only → Write-only property (e.g., password).
is
N
ith

44. Can you write a simple Java class that demonstrates encapsulation?
eW
od
C
45. How do access modifiers affect encapsulation?

●​ Private → fully hidden, best for encapsulation


●​ Protected → accessible to subclasses, partial access
●​ Default → accessible within package
●​ Public → breaks encapsulation if applied to variables

46. What is a POJO and how does it represent encapsulation?

Ans: POJO = Plain Old Java Object.

l
●​ Typically has private fields, public getters/setters, and no special annotations or logic.​

ha
●​ Represents encapsulation because fields are hidden and accessed only via
controlled methods.

hc
is
N
ith
eW
od

47. How does encapsulation support immutability? Give an example.

Ans: Encapsulation allows you to hide fields and prevent setters, creating objects that
cannot change state once created.
C
48. How can you make a class immutable using encapsulation?

●​ Make class final


●​ Make all fields private final
●​ Provide no setters, only getters
●​ Ensure mutable fields are cloned before returning

49. How does encapsulation help in teams or large codebases?

●​ Limits who can modify object state


●​ Reduces bugs and unintended side-effects
●​ Allows modular development, one team can work on getters/setters without breaking
others​

l
ha
50. Give a real-world example representing encapsulation.

hc
●​ ATM machine: You don’t see the internal code or money handling, you interact via
buttons/screens only.
●​ Analogy: Object state is hidden; access controlled via methods (APIs).
is
N
STAGE 3: Inheritance
ith

51. What is inheritance in Java?

Ans: Inheritance is an OOP concept where a class (child/subclass) acquires the


properties and behaviors of another class (parent/superclass). It promotes code reuse,
eW

extensibility, and establishes a hierarchical relationship between classes.


od
C
Here, Dog inherits eat() from Animal — no need to write it again.

52. Why do we use inheritance?

●​ Code Reuse: Avoid duplicating code across classes.


●​ Extensibility: New classes can be added with minimal changes.
●​ Polymorphism Support: Enables method overriding and runtime behavior changes.
●​ Logical Hierarchy: Helps model real-world relationships naturally.

Example: All vehicles share some features like start(). Instead of writing start() in each
vehicle class, create a parent Vehicle class, and child classes inherit it.

l
ha
53. What is the difference between IS-A and HAS-A relationships?

Type Description Example

hc
IS-A Inheritance relationship; subclass is a type of Dog IS-A Animal
superclass

HAS-A isComposition relationship; class has an object of Car HAS-A


another class Engine
N
ith
eW

●​ IS-A → inheritance
●​ HAS-A → composition
od

54. What different types of inheritance exist in Java? Explain each.

1.​ Single Inheritance: One class inherits from another.


C

2.​ Multilevel Inheritance: A chain of inheritance.


3.​ Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.​

l
ha
4.​ Multiple Inheritance (through interfaces): One class implements multiple
interfaces (because Java classes cannot extend multiple classes).​

hc
is
N
ith

55. Why is multiple inheritance not allowed in Java using classes?

Ans: Java does not allow multiple inheritance with classes to avoid ambiguity and the
eW

“Diamond Problem”.

Example of ambiguity:
od
C

Java avoids this problem by disallowing multiple class inheritance but allows
interfaces for multiple inheritance of behavior.​

56. How does Java support multiple inheritance using interfaces?

●​ A class can implement multiple interfaces, thus inheriting behavior from multiple
sources.
●​ This allows multiple inheritance of type/behavior, but not implementation conflicts.

l
ha
Here, C inherits contracts from both interfaces and provides its implementation.

57. What is the super keyword? Give an example.

hc
●​ super is a reference to the parent class.
●​ It is used to:
is1.​ Access parent class methods
2.​ Access parent class fields
3.​ Call parent class constructor
N
ith
eW
od
C

58. Can private members of a superclass be inherited? Why or why not?

Ans: Private members are not visible to subclasses, so they cannot be directly
inherited. However, they can be accessed indirectly via public/protected getters and
setters.​
l
ha
59. Can constructors be inherited?

Ans: No, constructors are not inherited, because a constructor is specific to the class.

hc
●​ Each class must define its own constructor.
●​ Subclasses can call superclass constructors using super().
is
60. What is constructor chaining in inheritance?
N
Ans:

●​ Constructor chaining is the process of calling one constructor from another.


ith

●​ In inheritance, a subclass constructor calls the parent constructor using


super().
●​ Ensures the parent part of the object is initialized first.​
eW
od
C

Output:

Parent constructor
Child constructor
B. Implementation / Coding Questions – Inheritance

61. Write a simple example of single inheritance (Parent → Child) in Java.

Ans: Single inheritance is when one class extends another. The child class inherits all
accessible fields and methods from the parent class.

l
ha
hc
is
N
ith
eW
od

Explanation:​
The Child class inherits greet() from Parent. This avoids code duplication and demonstrates
the IS-A relationship: Child IS-A Parent.
C

62. Write an example of multilevel inheritance (GrandParent → Parent → Child).

Ans: Multilevel inheritance is a chain where a class inherits from another, which in turn
inherits from another.
l
ha
hc
is
N
Explanation: Child inherits all methods from Parent and GrandParent, showing code reuse
and logical hierarchy.
ith

63. Show how to call the superclass constructor from a subclass.


eW

Ans: In Java, a subclass can call a parent class constructor using super(). This is
important for initializing parent class fields.
od
C

Output:
Parent Constructor
Child Constructor

64. Can we override a static method in Java? Explain with an example.


Ans: Static methods cannot be overridden. They belong to the class, not the instance.
If you define a static method with the same signature in a subclass, it’s called method
hiding, not overriding.

l
ha
hc
is
N
Output: Parent static

Explanation: The method is resolved at compile time, not runtime. True overriding requires
ith

instance methods.

65. What happens if a subclass defines a method with the same name but different
eW

parameters as the superclass?

Ans: This is called method overloading, not overriding.


od
C
Explanation:​
Overloaded methods are distinguished by parameters and are resolved at
compile-time.

66. Can a subclass access protected members of the superclass in another package?

Ans: ✅ Yes, but only through inheritance. Protected members are accessible to
subclasses even in different packages, but not through object references.

l
ha
hc
is
N
ith

Explanation: Protected allows subclass access across packages but maintains


eW

encapsulation.

67. Write an example demonstrating method overriding in Java.


od

Overriding happens when a subclass provides a new implementation for a


method inherited from the parent.
C
l
ha
hc
is
Output: Child show
N
Explanation: The child’s method is called at runtime, demonstrating dynamic polymorphism.
ith

68. Explain what happens when a subclass hides a superclass field with the same
name.

Ans: Field hiding occurs when a subclass declares a field with the same name as in
eW

its parent.
od
C

Explanation: Field hiding does not involve polymorphism; the reference type determines
which field is accessed.
69. How do you prevent a class from being subclassed?

Ans: Use the final keyword in the class.

Explanation:This ensures security and immutability in some cases (e.g., String class in
Java).

l
ha
70. Give a real-world example where inheritance improves code reuse and
maintainability.

hc
Ans: Consider a Vehicle superclass with start() and stop() methods. Subclasses like
Car, Bike, and Bus inherit these methods.
is
●​ No need to write start() in each class → code reuse
●​ Adding new vehicle types is easy → maintainability
●​ Polymorphism allows treating all vehicles uniformly:​
N
ith

Explanation: This avoids repetitive code and demonstrates hierarchy, reuse, and
eW

polymorphism together.
od
C
STAGE 4: Polymorphism
71. What is polymorphism in Java?

Ans: Polymorphism literally means “many forms”. In OOP, it allows a single


entity (method or object) to take multiple forms. It’s a way to design flexible and
extensible code where one interface can work with different types of objects.

Example:

l
ha
hc
is
N
ith
eW
od

Here, the same reference type Animal behaves differently depending on the actual object,
demonstrating polymorphism.
C

72. Why is polymorphism important in OOP?

Ans: Polymorphism is crucial because it:

1.​ Reduces code complexity: One method/interface can handle multiple object types.
2.​ Enhances flexibility and maintainability: New types can be added without changing
existing code.
3.​ Supports dynamic behavior: Subclass-specific behavior can replace superclass
behavior at runtime.
4.​ Encourages loose coupling: Code depends on interfaces or parent classes rather
than concrete implementations.
73. What are the two types of polymorphism in Java?

1.​ Compile-time (Static) Polymorphism


2.​ Runtime (Dynamic) Polymorphism
●​ Compile-time → resolved by the compiler (method overloading, operator overloading)
●​ Runtime → resolved at runtime (method overriding)

74. What is compile-time (static) polymorphism?

Ans: This occurs when the compiler decides which method to call at compile time. In
Java, this is mainly achieved by method overloading.

l
ha
hc
is
N
Explanation: The compiler selects the appropriate add method based on parameters — no
ith

runtime decision is needed.

75. What is runtime (dynamic) polymorphism?


eW

Ans: Runtime polymorphism occurs when the method that gets executed is decided at
runtime, not compile time. This is usually achieved using method overriding and
inheritance.
od
C

The JVM determines at runtime which sound() method to call based on the actual object
type (Dog).
76. How does method overloading achieve compile-time polymorphism?

Ans: By defining multiple methods with the same name but different parameters, the
compiler can determine which method to call based on argument types and count.

l
ha
hc
is
Explanation: The compiler resolves the method call during compilation → static
polymorphism.
N
77. How does method overriding achieve runtime polymorphism?
ith

Ans: When a subclass provides a specific implementation of a method inherited from


the parent class, the JVM decides at runtime which method to execute.
eW
od
C

This allows flexible behavior depending on the object.


78. Can constructors be overloaded? Is it polymorphism?



Ans: Yes, constructors can be overloaded (same name, different parameters).​
But constructor overloading is compile-time polymorphism, not runtime.

l
Explanation: The compiler decides which constructor to call based on parameters → static

ha
polymorphism.

79. Can private methods be overridden? Why or why not?

hc
Ans: No. Private methods belong to the class itself, not the subclass. They are not
visible outside the class, so overriding is impossible.

is
N
ith
eW

Here, Child.show() is not overriding, it’s a completely new method.

80. What is a covariant return type in method overriding?


od

Ans: Covariant return type allows the overridden method in subclass to return a
subtype of the superclass method’s return type.
C
81. What is the difference between method overloading and method overriding?
Feature Method Overloading Method Overriding

Definition Same method name but different Subclass provides a new


parameters in the same class (or implementation of a method from
subclass). its superclass.

Polymorphism Compile-time (static) Runtime (dynamic)


Type

Parameters Must be different (number or type Must be same (name, parameters).


of parameters).

l
ha
Return Type Can vary (but if types are same, Must be same or covariant return
no issue). type.

Access Modifier Any access modifier Cannot reduce visibility (can

hc
increase).

Exceptions Can throw any exception. Must not throw broader checked
is exceptions than superclass.

Example – Overloading:
N
class Calculator {
ith

int add(int a, int b) { return a+b; }


double add(double a, double b) { return a+b; }
}
eW

Example – Overriding:

class Animal {
void sound() { System.out.println("Some sound"); }
}
od

class Dog extends Animal {


@Override
void sound() { System.out.println("Bark"); }
}
C

82. Can private, final, or static methods be overridden? Why or why not?

Ans: Private methods → ❌ Cannot be overridden because they are not visible to
subclasses. They belong to the class itself.



●​ Final methods → Cannot be overridden because final prevents modification.
●​ Static methods → Cannot be overridden. Defining a static method with the same
name in a subclass hides the superclass method; it’s method hiding, not overriding.​
class Parent {
private void privateMethod() {}
final void finalMethod() {}
static void staticMethod() {}
}
class Child extends Parent {
// All above cannot be overridden
}

83. What is the difference between compile-time and runtime


polymorphism in terms of method binding?

l
Ans: 1. Compile-time polymorphism → Early binding

ha
○​ The compiler decides which method to call based on method signature
(overloading).

hc
2. Runtime polymorphism → Late binding

○​ JVM decides which method to call based on actual object type at runtime
is (overriding).

Example – Runtime (late binding):


N
Animal a = new Dog(); // actual type Dog
ith

a.sound(); // JVM calls Dog’s sound() at runtime

84. How does Java resolve which method to call at runtime in case of
overriding?
eW

●​ Java uses dynamic method dispatch: the JVM checks the actual object type (not
reference type) at runtime and invokes the overridden method of the subclass.
●​ Reference type determines what methods are visible, but object type determines
which implementation is executed.
od

Animal a = new Dog(); // Reference type: Animal, Object type: Dog


a.sound(); // JVM calls Dog's sound()
C

85. Can constructors participate in runtime polymorphism? Why or why not?

Ans: ❌ No. Constructors cannot be overridden, and hence cannot participate in


runtime polymorphism.

●​ Constructor is specific to the class it belongs to.


●​ JVM does not use dynamic method dispatch for constructors.
●​ Constructors are used only to initialize objects, not to provide polymorphic
behavior.​
86. What is dynamic method dispatch in Java, and how is it related to polymorphism?

Ans: Dynamic Method Dispatch (DMD) is the mechanism by which Java resolves
overridden method calls at runtime.

●​ It is the core of runtime polymorphism.


●​ JVM looks at actual object type and calls the appropriate method.

l
ha
Explanation:

hc
●​ Animal a reference → visible methods
●​ Dog object → actual method executed at runtime
is
87. How does polymorphism improve code maintainability and flexibility in large
applications?
N
●​ Decouples code from implementation: Code depends on interfaces or superclass, not
ith

specific implementations.
●​ Easy to extend: New classes can be added without changing existing logic.
●​ Reduces code duplication: Same method calls can work for multiple object types.
●​ Supports runtime flexibility: Behavior can change dynamically based on object type.​
eW

Example – Payment System:

interface Payment { void pay(double amount); }


od

class CreditCard implements Payment { public void pay(double amt){


System.out.println("Paid via card"); } }
C

class UPI implements Payment { public void pay(double amt){ System.out.println("Paid via
UPI"); } }

Payment p = new UPI();


p.pay(1000); // runtime decides which pay() method to execute
88. What is the difference between polymorphism in Java and C++?

Feature Java C++

Method Binding Compile-time & Runtime Compile-time & Runtime

Static Methods Cannot be overridden Can hide static methods (similar to


Java)

Virtual Keyword Not needed, all non-final Required to mark a method as virtual
instance methods are virtual for runtime polymorphism

Multiple Not allowed for classes, only Allowed for classes, can lead to

l
Inheritance via interfaces diamond problem

ha
Explanation: Java simplifies runtime polymorphism by making all instance methods virtual
by default.

hc
89. Can you override a superclass method and change its access modifier? What are
is
the rules?

●​ Rules for overriding access modifiers:​


N
1.​ You cannot reduce visibility.
ith

■​ public → always public in subclass


■​ protected → can be protected or public in subclass
■​ default/package-private → can become protected or public
2.​ You can increase visibility but not decrease it.
eW

✅ allowed
class Parent { protected void show() {} }
class Child extends Parent { public void show() {} } //

90. Give a real-world analogy to explain polymorphism in Java.


od

Ans: Analogy – Remote Control for Devices:

●​ One remote control can work for TV, AC, Fan.


C

●​ Pressing the “Power” button sends the same signal, but each device responds
differently: TV turns on, AC starts, Fan spins.

Explanation:

●​ The remote is like the reference type (superclass or interface)


●​ The device is like the actual object​

●​ Dynamic method dispatch decides what happens when the “Power” button is pressed
→ runtime polymorphism.
STAGE 5: Abstraction

91. What is abstraction in Java?

Ans: Abstraction is the OOP concept of hiding implementation details and showing only
essential functionality to the user. It allows you to focus on what an object does, not how it
does it.

●​ Example analogy: When you drive a car, you just press the accelerator, brake, or
steering; you don’t need to know how the engine works internally.
●​ In Java, abstraction is implemented using abstract classes and interfaces.​

l
ha
92. How is abstraction different from encapsulation?

Feature Abstraction Encapsulation

hc
Purpose Hides implementation details, Hides internal state and protects
shows only functionality data from direct access

How is Abstract classes, Interfaces Access modifiers (private,


implemented protected) + getters/setters
N
Focus “What an object does” “How an object stores/manages its
data”
ith

Example Vehicle class exposes start() but Car class makes speed private and
hides engine details provides getSpeed()
eW

93. Why do we need abstraction in OOP?

●​ To reduce complexity by exposing only essential operations.


●​ To increase code reusability; different implementations can be used without
od

changing client code.


●​ To support polymorphism; the same interface can represent multiple types.
●​ To improve maintainability; changes to implementation do not affect the client.
C

94. What is an abstract class in Java?

●​ A class declared with the abstract keyword.


●​ Can contain abstract methods (no body) and concrete methods (with body).
●​ Cannot be instantiated directly.
●​ Designed to be extended by subclasses that provide implementations for abstract
methods.


95. Can an abstract class have a constructor? If yes, why is it useful?

Ans: ✅ Yes, abstract classes can have constructors.


●​ Why: Constructors are used to initialize fields common to all subclasses.
●​ Example: If Vehicle is abstract, its constructor can initialize speed and fuelType, and
all subclasses like Car and Bike will inherit these initializations.​

96. Can an abstract class have both abstract and non-abstract (concrete) methods?

✅ Yes.

l
●​ Abstract methods define what subclasses must implement.

ha
●​ Concrete methods provide default behavior that can be reused.

Example: Vehicle has start() abstract, but stop() concrete. Subclasses implement start(),
and inherit stop().

hc
97. Can you instantiate an abstract class? Why or why not?

❌ No, you cannot directly create an object of an abstract class.


is
●​ Reason: Abstract class may have incomplete implementations (abstract methods),
N
so it doesn’t define a complete object.
●​ You must extend it in a subclass and implement abstract methods to instantiate.
ith

98. What is an interface in Java?

●​ An interface is a pure abstraction mechanism that defines a contract — methods


eW

that a class must implement.


●​ From Java 8 onwards, interfaces can also have default, static, and private
methods.
●​ A class can implement multiple interfaces, supporting multiple inheritance.
od

99. Can interfaces have method implementations in Java? If yes, how (default, static,
private methods)?

Ans: ✅ Yes:
C

●​ Default methods: have a body, can be inherited by implementing classes, can be


overridden.
●​ Static methods: belong to interface, cannot be overridden by implementing classes.
●​ Private methods: used inside interface to share code among default methods, not
accessible outside.​

100. What is the difference between an abstract class and an interface in Java?
Feature Abstract Class Interface

Multiple ❌ No ✅ Yes
inheritance

Methods Abstract + concrete Default, static, abstract (all methods are public
by default)

Variables Instance variables Only public static final (constants)


allowed

Constructor Allowed ❌ Not allowed

l
ha
Access modifiers Any Methods: public by default, can have private
(Java 9+)

hc
101. Can a class extend multiple abstract classes? Why or why not?

Ans: ❌ No, Java does not support multiple inheritance of classes (abstract or concrete)
is
to avoid diamond problem.

●​ Solution: Use interfaces to achieve multiple inheritance.


N
102. Can a class implement multiple interfaces? How is this different from multiple
ith

inheritance in classes?

Ans: ✅ Yes.
eW

●​ A class can implement multiple interfaces.


●​ Unlike multiple class inheritance, there’s no diamond problem, because interfaces
contain no state (mostly abstract methods).

103. Can an interface extend another interface? Can it extend multiple interfaces?
od

Ans: ✅ Yes.
●​ One interface can extend multiple interfaces.
C

●​ This allows combining multiple contracts into a single interface.

104. Can an abstract class implement an interface? Explain.

Ans: ✅ Yes.
●​ An abstract class can implement an interface partially (provide some method
implementations) and leave the rest to subclasses.
105. What is the purpose of default methods in interfaces?

●​ Introduced in Java 8 to allow adding new methods to interfaces without breaking


existing implementations.
●​ Provides concrete behavior in interfaces.

106. Can static methods in interfaces be overridden in implementing classes? Why or


why not?

Ans: ❌ No.
●​ Static methods belong to interface itself, not instances.
●​ They cannot participate in polymorphism or be overridden.

l
ha
107. Can a private method exist in an interface? How is it used?

✅ Yes, Java 9+ allows private methods in interfaces.

hc
Ans:

●​ Purpose: reusable code among default and static methods, keeping


is
implementation hidden.

108. Can you declare variables in an interface? What are their default modifiers?
N
Ans: Yes, all variables in an interface are implicitly:
ith

○​ public
○​ static
○​ final (constant)
eW

●​ They cannot be instance variables.

109. How does abstraction help achieve polymorphism in Java?

Ans:
od

●​ By exposing common interfaces or abstract classes, client code can treat


different concrete objects uniformly.
●​ Example: Shape s = new Circle(); Shape s2 = new Rectangle(); s.draw(); → same
C

method call, different behavior at runtime.

110. How does abstraction improve code maintainability, flexibility, and scalability in
large projects?

●​ Maintainability: Changes in concrete implementations don’t affect clients.


●​ Flexibility: New classes can implement interfaces without changing existing code.
●​ Scalability: Supports polymorphism, allowing a system to grow and integrate new
modules easily.​
STAGE 6: Object Relationships

111. What is object association in Java?

Ans: Association defines a relationship between two separate classes that are
connected through their objects.​
It represents a “uses-a” or “works-with” relationship.​
Example: A Teacher teaches multiple Students. Both can exist independently.

112. What is aggregation? How is it different from association?

Ans: Aggregation is a special form of association that represents a “has-a” relationship with

l
shared ownership.

ha
●​ Both objects can exist independently.
●​ Example: A Library has Books. If the Library is deleted, the Books can still exist.

hc
Difference:

●​ Association = General relationship


●​ Aggregation = Whole–part relationship with independent lifecycles
is
113. What is composition? How is it different from aggregation?
N
Ans: It is a strong form of aggregation where one object cannot exist without the other.
ith

●​ Example: A House has Rooms. If the House is destroyed, the Rooms are too.
●​ Lifecycle: A child object’s lifecycle is bound to the parent.
eW

Difference:

●​ Aggregation → weak relationship (independent lifecycles)


●​ Composition → strong relationship (dependent lifecycle)
od

114. Can you give real-world examples of association, aggregation, and composition?

Relationship Type Real-World Example Description


C

Association Teacher ↔ Student Both exist independently but interact

Aggregation Library → Book Books can exist even if library closes

Composition House → Room Rooms don’t exist without the house


115. What is the difference between HAS-A and IS-A relationships?

Type Description Example

IS-A Inheritance relationship between classes Dog is a Animal

HAS-A Association or composition relationship Car has a Engine

l
Key Difference:

ha
●​ IS-A: established via extends (inheritance)
●​ HAS-A: established via object references (composition/aggregation)

hc
116. When should you prefer composition over inheritance?

Ans: Prefer composition when:

●​
●​
is
You want flexibility and loose coupling.
Behavior should be changed at runtime (by replacing components).
N
●​ You don’t want to expose all superclass behavior.
●​ Example: Instead of inheriting Engine, Car has an Engine object → you can easily
ith

swap engine types.

117. What is dependency in OOP?


eW

Ans: Dependency means one class depends on another to perform its function.​
It’s a temporary association (used only when needed).​
Example: Driver depends on Car to drive → if car changes, driver’s behavior may change.

118. How does dependency differ from aggregation?


od

Concept Dependency Aggregation


C

Nature Temporary (method-level) Structural (class-level)

Lifetime Exists during method execution Exists as a class member

Example PaymentService depends on Library aggregates Book objects


BankAPI
119. Can a class have multiple associations with another class?

Ans: ✅ Yes.​
A class can have multiple associations with another class if they represent different roles
or relationships.​
Example:

●​ A Teacher may teach a Student (association 1)


●​ A Teacher may also mentor a Student (association 2)

So, multiple associations between the same classes are allowed if their purpose differs.

l
ha
120. Can aggregation exist without a “has-a” relationship?

Ans: ❌ No.​

hc
Aggregation always implies a “has-a” relationship because it represents ownership or
whole-part structure.​
If two classes are only loosely connected without ownership, that’s a simple association,
not aggregation.
is
✅ Summary Table for Quick Recall:
N
ith

Relationship Type Ownership Lifecycle Example


Dependency
eW

Association Uses-a No Independent Teacher–Studen


t
od

Aggregation Has-a (weak) Shared Independent Library–Book


C

Compositio Has-a (strong) Exclusive Dependent House–Room


n

Dependency Uses temporarily No Temporary Driver–Car


Stage 7: Important OOP Keywords

121. Can a constructor be declared final, static, or abstract? Why or why not?

Ans: No.

●​ final: Constructors are not inherited, so making them final makes no sense.
●​ static: Constructors are called to create objects, but static methods belong to the
class, not objects.
●​ abstract: Constructors must have a body, while abstract methods don’t.

Hence, none of these modifiers are valid for constructors.

l
ha
122. Can we use this() and super() together in the same constructor? Why or why not?

hc
Ans: No. Both this() and super() must be the first statement inside a constructor.​
Java doesn’t allow two first statements, so you can only call one — either another
constructor of the same class (this()) or the parent constructor (super()).
is
123. What is the difference between a static block and an instance initializer block?
N
Feature Static Block Instance Initializer Block

When executed Once when class is Every time an object is created


ith

loaded

Access to instance ❌ No ✅ Yes


members
eW

Use case Initialize static Common initialization code for all


variables constructors

Example:
od

class Demo {
static { System.out.println("Static block"); }
C

{ System.out.println("Instance block"); }
}

Output (for 2 objects):

Static block
Instance block
Instance block
124. What happens if you declare a static variable inside a method?

Ans: It’s not allowed in Java.​


Static variables belong to a class, not to a specific method.​
Local variables inside methods are stored in the stack, while static variables live in the
method area (class memory) — hence they can’t coexist in a local context.

125. Can a class be both abstract and final at the same time?

Ans: No.

●​ abstract → means “incomplete” and must be subclassed.


●​ final → means “cannot be subclassed.”​

l
ha
These are opposite in meaning, so Java doesn’t allow both together.

126. Can a static method be abstract? Why or why not?

hc
Ans: No.​
Static methods belong to the class, while abstract methods are meant to be overridden by
subclasses.​
Since static methods cannot be overridden, combining static and abstract makes no sense.
is
127. Can a static method access non-static data members or methods?
N
Ans: No, because static methods belong to the class, not to any particular object.​
They can only access static members directly.​
ith

To access instance variables, they must create an object first.

Example:
eW

class Test {
int x = 5;


static void show() {
// System.out.println(x); Not allowed


Test obj = new Test();
od

System.out.println(obj.x); // Allowed
}
}
C

128. What happens if you call this() or super() from a normal method (not a
constructor)?

Ans: You cannot call this() or super() from a normal method — it causes a compile-time
error. These calls are only allowed inside constructors, and must be the first statement.

✅ Why?​
Because this() and super() are used to control object construction — they determine which
constructor is executed first in the chain. Once the object is constructed, there’s no need (or
logical sense) to invoke them again.
129. Can you override a method and make it static in the subclass?

Ans: No.​
A static method cannot be overridden, because static methods are class-level — not tied to
an object.​
However, you can redeclare a static method in the subclass — this is called method hiding,
not overriding.

Example:

class Parent {
static void show() { System.out.println("Parent"); }
}

l
ha
class Child extends Parent {
static void show() { System.out.println("Child"); }
}

hc
Here, calling Parent.show() prints Parent, and Child.show() prints Child,​
but polymorphism does not apply — method resolution happens at compile time.

130. What happens if you make an interface variable non-final or non-static?


is
Ans: It’s not allowed in Java.​
N
All variables declared inside an interface are implicitly:(public, static, final )

That means they behave like constants shared by all implementing classes.​
ith

You cannot make them non-static or non-final, nor can you reassign their values in
implementation classes.

✅ Summary Table:
eW

Keyword Meaning Can combine with

this Refers to current object Used inside instance methods or


od

constructors

super Refers to parent class Used to access parent


methods/constructors
C

final Prevent modification Works with classes, methods, variables

static Belongs to class, not instance Variables, methods, blocks, nested


classes

abstract Incomplete element to be Classes, methods


implemented
STAGE 8: Comparison-Based Topics

131. Difference between Method Overloading and Method Overriding

Ans: Method Overloading happens when multiple methods in the same class have the same
name but different parameters (type, number, or order).​
Method Overriding occurs when a subclass provides a new implementation for a method
that is already defined in its superclass.

Aspect Overloading Overriding

Binding Compile-tim Runtime

l
Time e

ha
Parameters Must differ Must be same

Return Type Can differ Must be same or

hc
covariant

Inheritance Not required Requires inheritance


is
N
132. Difference between Compile-time Polymorphism and Runtime Polymorphism

Ans:
ith

1. Compile-time Polymorphism (Static Polymorphism)​


Compile-time polymorphism occurs when the method to be executed is decided at compile


time.How it is achieved:​
eW

Achieved through Method Overloading (same method name, different parameter


lists).Example:
od
C
2. Runtime Polymorphism (Dynamic Polymorphism)

Definition: Runtime polymorphism occurs when the method to be executed is decided at


runtime.


How it is achieved:​
Achieved through Method Overriding (same method name and parameters in parent and
child classes).

l
ha
hc
is
N
ith

Basis Compile-time Polymorphism Runtime Polymorphism

Definition Method call resolved at compile Method call resolved at


eW

time runtime

Achieved By Method Overloading Method Overriding

Binding Type Static Binding / Early Binding Dynamic Binding / Late


od

Binding

Decision Made By Compiler JVM (Java Virtual Machine)


C

Speed Faster Slightly Slower

Inheritance Not required Required (Parent–Child


Required Relationship)

Example void show(int a), void Animal → Dog overriding


show(double b) sound()

Flexibility Less flexible (fixed at compile More flexible (decided at


time) runtime)
3. Difference between Static Binding and Dynamic Binding

Ans: Static Binding is determined at compile-time (used by static, private, and final
methods).​
Dynamic Binding is determined at runtime for overridden instance methods.

Aspect Static Binding Dynamic Binding

Resolved by Compiler JVM

Methods Static, final, private Overridden


methods

l
ha
Polymorphism No Yes

134. Difference between Constructor Overloading and Method Overloading

hc
Ans: Both use the same name with different parameters, but constructors initialize objects
while methods perform actions.

Aspect
is Constructor Overloading Method Overloading

Purpose Initialize objects Perform actions


N
Return Type None Can have any
ith

Called by new keyword Directly invoked

135. Difference between Constructor and Method Overriding (and why constructors
eW

can’t be overridden)

Ans: Constructors cannot be overridden because they are not inherited. Each class has its
own constructors that are called via super().
od

Aspect Constructor Method

Inherited No Yes
C

Overridable No Yes

Purpose Object creation Behavior definition


136. Difference between Instance Method and Static Method (in the context of
polymorphism)

Ans: Instance Methods are tied to objects and participate in runtime polymorphism.​
Static Methods are tied to the class and resolved at compile-time.

Aspect Instance Method Static Method

Belongs To Object Class

Polymorphism Supported Not supported

Binding Dynamic Static

l
ha
137. Difference between Superclass Reference and Subclass Reference Behavior in
Runtime Polymorphism

hc
Ans: A superclass reference can refer to a subclass object, enabling runtime polymorphism.​
At runtime, the actual object’s overridden method is executed.

Example: is
Parent p = new Child();
N
p.show(); // Executes Child’s show()
ith

Aspect Superclass Reference Subclass Reference

Access Only superclass All subclass members


members
eW

Method Execution Depends on object type Direct subclass


methods
od

138. Difference between Abstract Class and Interface

Ans: Abstract Class provides partial abstraction (can have both abstract & concrete
methods).​
C

Interface provides full abstraction (only contracts).

Aspect Abstract Class Interface

Methods Abstract + Concrete Abstract (and default/static)

Constructors Allowed Not allowed

Multiple Inheritance Not supported Supported


139. Difference between Final Class and Abstract Class

Ans: Final Class cannot be extended — represents complete behavior.​


Abstract Class must be extended — represents incomplete behavior.

Aspect Final Class Abstract Class

Inheritance Not allowed Required

Purpose Restrict modification Enforce implementation

140. Difference between Interface Inheritance and Class Inheritance

l
ha
Ans: Interface Inheritance allows multiple inheritance and defines only contracts.​
Class Inheritance allows single inheritance and includes data and behavior.

hc
Aspect Interface Inheritance Class Inheritance

Multiple Inheritance Allowed Not allowed

Members
is Methods only Methods + Variables
N
SHOW SOME LOVE BY FOLLOWING CodeWithNishchal:
ith

○​ Instagram: https://www.instagram.com/codewithnishchal/
○​ LinkedIn: https://www.linkedin.com/in/nishchal-muradia/
○​ YouTube: https://www.youtube.com/@CodeWithNishchal
eW

○​ Watch My Latest Time Complexity Series: Time Complexity on YT


od
C

You might also like