Object-Oriented Programming (OOPs) - Complete Interview
Guide
Table of Contents
1. Basic OOPs Concepts
2. Core Principles
3. Advanced Concepts
4. Java-Specific OOPs
5. C++ Specific OOPs
6. Design Patterns
7. Practice Questions
Basic OOPs Concepts
1. What is Object-Oriented Programming?
Answer: Object-Oriented Programming (OOP) is a programming paradigm that organizes code around
objects rather than functions. It's based on the concept of "objects" which contain data (fields/attributes)
and methods (functions) that operate on that data.
2. What is a Class?
Answer: A class is a blueprint or template for creating objects. It defines the structure and behavior that
the objects will have. It contains:
Attributes (data members)
Methods (member functions)
Constructors
Destructors (in C++)
Example:
java
public class Car {
brand;;
private String brand
speed;;
private int speed
Car((String brand
public Car brand)) {
this..brand = brand
this brand;;
this..speed = 0;
this
}
accelerate(() {
public void accelerate
10;;
speed += 10
}
}
3. What is an Object?
Answer: An object is an instance of a class. It's a concrete entity created from a class blueprint that has
actual values for its attributes and can execute methods.
4. What is the difference between Class and Object?
Answer:
Class: Blueprint/template, no memory allocated, logical entity
Object: Instance of class, memory allocated, physical entity
One class can have multiple objects
5. What are the main features of OOPs?
Answer: The four main pillars of OOPs are:
1. Encapsulation - Data hiding and bundling
2. Inheritance - Code reusability through parent-child relationship
3. Polymorphism - Same interface, different implementations
4. Abstraction - Hiding complex implementation details
Core Principles
Encapsulation
6. What is Encapsulation?
Answer: Encapsulation is the bundling of data (attributes) and methods that operate on that data within
a single unit (class). It also involves data hiding by making attributes private and providing public
methods to access them.
7. How is Encapsulation achieved?
Answer:
Make data members private
Provide public getter and setter methods
Control access to internal data
Example:
java
public class BankAccount {
balance;; // Private data
private double balance
getBalance(() {
public double getBalance // Public getter
balance;;
return balance
}
public void deposit(
deposit(double amount)
amount) { // Public method
if((amount > 0) {
if
amount;;
balance += amount
}
}
}
8. What are Access Modifiers?
Answer:
Public: Accessible from anywhere
Private: Accessible only within the same class
Protected: Accessible within package and subclasses
Default/Package: Accessible within the same package
Inheritance
9. What is Inheritance?
Answer: Inheritance is a mechanism where a new class (child/derived) acquires properties and behaviors
of an existing class (parent/base). It promotes code reusability.
10. Types of Inheritance?
Answer:
1. Single Inheritance: One parent, one child
2. Multiple Inheritance: One child, multiple parents (not in Java)
3. Multilevel Inheritance: Chain of inheritance
4. Hierarchical Inheritance: One parent, multiple children
5. Hybrid Inheritance: Combination of above types
'3MKTKXGR3XKRGZOUTYNOV3
11. What is the difference between Inheritance and Composition?
HKZ]KKT3Z]U3IRGYYKY3
]NKXK3UTK3[YKY3UX3 Answer:
OTZKXGIZY3]OZN3GTUZNKX
Inheritance (IS-A): Child class is a type of parent class
4GZ[XK 32UUYKR_3IU[VRKJ!3
TU3U]TKXYNOV3OSVROKJ
Composition (HAS-A): Class contains objects of other classes
F Example:
'MMXKMGZOUT3=KGQ3.'9'
java
*KLOTOZOUT 3'3YVKIOGRO`KJ3LUXS3
UL3GYYUIOGZOUT3]NKXK3UTK3IRGYY3 // Inheritance
IUTZGOTY3GTUZNKX3H[Z3ZNK3
class Animal { }
IUTZGOTKJ3UHPKIZ3IGT3K^OYZ3
OTJKVKTJKTZR_
class Dog extends Animal { } // Dog IS-A Animal
4GZ[XK 36GXZOGR3U]TKXYNOV!3ZNK3 // Composition
INORJ3IGT3U[ZRO\K3ZNK3VGXKTZ
class Engine { }
+^GSVRK 3'32OHXGX_3
class Car {
GMMXKMGZKY3(UUQY3/L3ZNK3 engine;; // Car HAS-A Engine
private Engine engine
ROHXGX_3OY3JKRKZKJ3ZNK3HUUQY3 }
YZORR3K^OYZ3KRYK]NKXK
12. What is Method Overriding?
狥3)USVUYOZOUT39ZXUTM3.'9'
*KLOTOZOUT 3'3YZXUTMKX3LUXS3UL3 Answer: Method overriding occurs when a subclass provides a specific implementation of a method that
GMMXKMGZOUT3]NKXK3ZNK3VGXKTZ3
is already defined in its parent class.
IRGYY3L[RR_3U]TY3ZNK3INORJ3GTJ3
IRGYY3(GTQ'IIU[TZ3a
ZNK3INORJ狭Y3ROLKI_IRK3OY3ZOKJ3ZU3ZNK3 3333V[HROI3\UOJ3IGRI[RGZK/TZKXKYZ3a
Rules: 333333339_YZKSU[ZVXOTZRT8)GRI[RGZOTM3OTZKXKYZ3GZ3HGYK3
VGXKTZ
XGZK8!
4GZ[XK 3:OMNZ3IU[VROTM!3JKRKZOUT3 Same method signature
3333c
UL3VGXKTZ3SKGTY3JKRKZOUT3UL3INORJ
@Override annotation (Java) c
Runtime polymorphism 39[HIRGYY
;YK3&5\KXXOJK3GTTUZGZOUT3ZU3 IRGYY39G\OTMY'IIU[TZ3K^ZKTJY3(GTQ'IIU[TZ3a
IGZIN3KXXUXY3GZ3IUSVORK3ZOSK 13. Can we override static methods? 3333&5\KXXOJK
3333V[HROI3\UOJ3IGRI[RGZK/TZKXKYZ3a
5\KXXOJJKT3SKZNUJY3S[YZ3NG\K3 Answer: No, static methods cannot be overridden because they belong to the class, not to instances.
333333339_YZKSU[ZVXOTZRT8)GRI[RGZOTM3OTZKXKYZ3LUX3
ZNK3YGSK3YOMTGZ[XK
However, they can be hidden in subclasses. YG\OTMY3GIIU[TZ3GZ3狦 8!
8KZ[XT3Z_VK3S[YZ3HK3ZNK3YGSK3 3333c
UX3IU\GXOGTZ3OK3Y[HIRGYY3UL3 Polymorphism c
UXOMOTGR3XKZ[XT3Z_VK
14. What is Polymorphism?
'IIKYY3SUJOLOKX3S[YZ3HK3KW[GR3
UX3RKYY3XKYZXOIZO\K
Answer: Polymorphism means "many forms." It allows objects of different types to be treated as objects
?U[3IGTTUZ3U\KXXOJK3YZGZOI3
of a common base type, with each type implementing behavior differently.
LOTGR3UX3VXO\GZK3SKZNUJY
15. Types of Polymorphism?
Answer:
1. Compile-time Polymorphism (Static):
Method Overloading
Operator Overloading
2. Runtime Polymorphism (Dynamic):
Method Overriding
Virtual functions
16. What is Method Overloading?
Answer: Method overloading allows multiple methods with the same name but different parameters
(number, type, or order) in the same class.
Example:
java
public class Calculator {
public int add(
add(int a,
a, int b)
b) {
b;;
return a + b
}
add((double a
public double add a,, double b
b)) {
b;;
return a + b
}
add((int a
public int add a,, int b
b,, int cc)) {
return a + b + cc;;
}
}
17. Difference between Overloading and Overriding?
Answer:
Overloading Overriding
Compile-time Runtime
Same class Different classes (inheritance)
Different parameters Same parameters
Static polymorphism Dynamic polymorphism
Abstraction
18. What is Abstraction?
Answer: Abstraction is the process of hiding implementation details while showing only essential
features to the user. It focuses on what an object does rather than how it does it.
19. How is Abstraction achieved?
Answer:
Abstract classes - Cannot be instantiated, can have abstract and concrete methods
Interfaces - Contract that classes must follow
20. Difference between Abstract Class and Interface?
Answer:
Abstract Class Interface
Can have concrete methods Only abstract methods (Java 8+ allows default)
Can have constructors Cannot have constructors
Can have instance variables Only constants (final static)
Single inheritance Multiple inheritance
extends keyword implements keyword
Advanced Concepts
21. What is a Constructor?
Answer: A constructor is a special method that initializes objects when they are created. It has the same
name as the class and no return type.
22. Types of Constructors?
Answer:
1. Default Constructor: No parameters
2. Parameterized Constructor: Takes parameters
3. Copy Constructor: Creates object from another object (C++)
23. What is Constructor Chaining?
Answer: Constructor chaining is calling one constructor from another constructor in the same class
(this()) or parent class (super()).
24. What is a Destructor?
Answer: A destructor is a special method that cleans up resources when an object is destroyed. Available
in C++ (~ClassName()), Java has finalize() but uses garbage collection.
25. What is Method Overriding vs Method Hiding?
Answer:
Overriding: Instance methods, runtime polymorphism
Hiding: Static methods, compile-time resolution
26. What is Dynamic Binding?
Answer: Dynamic binding (late binding) is when the method to be called is determined at runtime based
on the actual object type, not the reference type.
27. What is Static Binding?
Answer: Static binding (early binding) is when the method to be called is determined at compile time.
Used for static methods, private methods, and final methods.
28. What is the Diamond Problem?
Answer: The diamond problem occurs in multiple inheritance when a class inherits from two classes that
both inherit from the same base class, creating ambiguity. Java solves this by not allowing multiple class
inheritance.
29. What is Composition vs Aggregation?
Answer:
Composition (Strong HAS-A): Parent owns child, child cannot exist without parent
Aggregation (Weak HAS-A): Parent uses child, child can exist independently
30. What is Association?
Answer: Association represents a relationship between two separate classes through their objects. It can
be one-to-one, one-to-many, many-to-one, or many-to-many.
Java-Specific OOPs
31. What is the super keyword?
Answer: The super keyword refers to the immediate parent class object. Used to:
Call parent class methods: super.methodName()
Call parent class constructor: super()
Access parent class variables: super.variableName
32. What is the this keyword?
Answer: The this keyword refers to the current object instance. Used to:
Refer to current class variables
Call current class methods
Call current class constructors: this()
33. What is final keyword?
Answer:
final variable: Cannot be reassigned (constant)
final method: Cannot be overridden
final class: Cannot be inherited (e.g., String class)
34. What is static keyword?
Answer: Static members belong to the class rather than any instance:
static variable: Shared among all instances
static method: Can be called without creating object
static block: Executed when class is first loaded
35. Can we override static methods in Java?
Answer: No, static methods cannot be overridden. They can be hidden if redefined in subclass, but it's
not true overriding.
36. What is instanceof operator?
Answer: The instanceof operator tests whether an object is an instance of a specific class or implements
an interface.
java
String)) {
if (obj instanceof String
// obj is a String
}
37. What is Object class in Java?
Answer: Object is the root class of all classes in Java. Every class directly or indirectly inherits from Object
class. Key methods:
toString()
equals()
hashCode()
getClass()
clone()
38. What is Method Overriding rules in Java?
Answer:
Method signature must be same
Return type must be same or covariant
Access modifier cannot be more restrictive
Cannot override final, static, or private methods
Must handle same or fewer exceptions
C++ Specific OOPs
39. What is Virtual Function?
Answer: Virtual functions enable runtime polymorphism. When a virtual function is called through a base
class pointer/reference, the actual method of the derived class is called.
cpp
class Base {
public:
public:
show(() {
virtual void show
cout << "Base class";
class";
}
};
class Derived : public Base {
public::
public
show(() override {
void show
cout << "Derived class";
class";
}
};
40. What is Pure Virtual Function?
Answer: A pure virtual function is declared by assigning 0 to the virtual function. Classes with pure virtual
functions become abstract and cannot be instantiated.
cpp
display(() = 0; // Pure virtual function
virtual void display
41. What is Virtual Destructor?
Answer: Virtual destructors ensure that the destructor of derived class is called when deleting object
through base class pointer.
42. What is Multiple Inheritance in C++?
Answer: C++ supports multiple inheritance where a class can inherit from multiple base classes.
cpp
class A { };
class B { };
class C : public A, public B { }; // Multiple inheritance
43. What is Virtual Base Class?
Answer: Virtual base class is used to avoid multiple copies of the same base class in diamond inheritance
problem.
cpp
class A { };
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { }; // Only one copy of A
Design Patterns
44. What is Singleton Pattern?
Answer: Singleton ensures that a class has only one instance and provides global access to it.
java
public class Singleton {
instance;;
private static Singleton instance
Singleton(() {} // Private constructor
private Singleton
getInstance(() {
public static Singleton getInstance
null)) {
if (instance == null
Singleton(();
instance = new Singleton
}
instance;;
return instance
}
}
45. What is Factory Pattern?
Answer: Factory pattern creates objects without specifying their exact classes. It provides an interface for
creating objects in a superclass.
46. What is Observer Pattern?
Answer: Observer pattern defines a one-to-many dependency between objects so that when one object
changes state, all dependents are notified automatically.
Practice Questions
47. Can we have multiple main methods in Java?
Answer: Yes, we can have multiple main methods through method overloading, but JVM will only call the
one with signature: public static void main(String[] args)
48. What happens if we don't provide a constructor?
Answer: The compiler automatically provides a default no-argument constructor that initializes objects
with default values.
49. Can constructors be private?
Answer: Yes, private constructors are used in Singleton pattern and utility classes to prevent instantiation.
50. What is Constructor Overloading?
Answer: Having multiple constructors in the same class with different parameter lists.
51. Can we override constructors?
Answer: No, constructors cannot be overridden because they are not inherited. However, they can be
overloaded.
52. What is the difference between == and equals()?
Answer:
== compares references (memory addresses)
equals() compares content/values
53. What is hashCode() method?
Answer: hashCode() returns an integer representation of the object's memory address. Objects that are
equal must have the same hash code.
54. What is Covariant Return Type?
Answer: Covariant return type allows overridden method to return a subtype of the return type declared
in the overridden method.
55. What is Method Hiding?
Answer: When a subclass defines a static method with the same signature as a static method in the
superclass, it hides the parent method.
56. What is Early Binding vs Late Binding?
Answer:
Early Binding: Method calls resolved at compile time (static, private, final methods)
Late Binding: Method calls resolved at runtime (virtual methods)
57. What is Shadowing?
Answer: When a subclass variable has the same name as a superclass variable, the subclass variable
shadows the superclass variable.
58. Can we have abstract methods in non-abstract class?
Answer: No, if a class has abstract methods, the class must be declared abstract.
59. What is the use of protected access modifier?
Answer: Protected members are accessible within the same package and by subclasses, even if they're in
different packages.
60. What is IS-A and HAS-A relationship?
Answer:
IS-A (Inheritance): Dog is an Animal
HAS-A (Composition): Car has an Engine
61. What is Multiple Inheritance and why Java doesn't support it?
Answer: Multiple inheritance allows a class to inherit from multiple classes. Java doesn't support it to
avoid:
Diamond problem
Complexity in method resolution
Ambiguity in multiple parent methods
62. What is Interface in Java?
Answer: Interface is a contract that defines what methods a class must implement. It achieves multiple
inheritance of type.
63. Can interface have constructors?
Answer: No, interfaces cannot have constructors because they cannot be instantiated.
64. What are default methods in Java 8?
Answer: Default methods allow interfaces to have method implementations without breaking existing
implementations.
java
interface MyInterface {
defaultMethod(() {
default void defaultMethod
System..out
System out..println
println(("Default implementation")
implementation");
}
}
65. What is Marker Interface?
Answer: An interface with no methods. Examples: Serializable, Cloneable, Remote. Used to mark classes
for special treatment.
66. What is Functional Interface?
Answer: An interface with exactly one abstract method. Can be used with lambda expressions. Examples:
Runnable, Callable, Comparator.
67. What is Abstract Class vs Concrete Class?
Answer:
Abstract Class: Cannot be instantiated, may have abstract methods
Concrete Class: Can be instantiated, all methods implemented
68. Can abstract class have constructors?
Answer: Yes, abstract classes can have constructors. They're called when a subclass object is created.
69. What is Nested Class?
Answer: A class defined inside another class. Types:
Static nested class
Inner class (non-static)
Local class
Anonymous class
70. What is Anonymous Class?
Answer: A class without a name, defined and instantiated at the same time. Often used for implementing
interfaces or extending classes for one-time use.
71. What is SOLID Principles?
Answer:
S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
72. What is Liskov Substitution Principle?
Answer: Objects of a superclass should be replaceable with objects of a subclass without breaking the
application.
73. What is Dependency Injection?
Answer: A design pattern where objects receive their dependencies from external sources rather than
creating them internally.
74. What is Tight Coupling vs Loose Coupling?
Answer:
Tight Coupling: Classes are highly dependent on each other
Loose Coupling: Classes have minimal dependencies, easier to maintain
75. What is Object Cloning?
Answer: Creating an exact copy of an object. Java provides clone() method in Object class. Types:
Shallow Copy: Copies object references
Deep Copy: Copies actual objects
76. What is Serialization?
Answer: Converting object state into byte stream for storage or transmission. Class must implement
Serializable interface.
77. What is transient keyword?
Answer: transient keyword prevents variables from being serialized. Transient variables are not included
in serialization process.
78. What is volatile keyword?
Answer: volatile ensures that variable value is always read from main memory, not from thread's local
cache. Used in multi-threading.
79. What is synchronized keyword?
Answer: synchronized provides thread safety by allowing only one thread to access the method/block at
a time.
80. What is Immutable Class?
Answer: A class whose objects cannot be modified after creation. Example: String class.
Rules for Immutable Class:
Make class final
Make all fields private and final
Don't provide setter methods
Return copies of mutable objects
81. What is String Pool?
Answer: String pool is a special memory area where String literals are stored. It helps in memory
optimization by reusing strings.
82. Why String is immutable?
Answer:
Security (used in network connections, file paths)
Thread safety
Caching (hashcode)
String pool optimization
83. What is StringBuilder vs StringBuffer?
Answer:
StringBuffer: Thread-safe, synchronized
StringBuilder: Not thread-safe, faster performance
84. What is Garbage Collection?
Answer: Automatic memory management that reclaims memory used by objects that are no longer
reachable or referenced.
85. What is finalize() method?
Answer: finalize() is called by garbage collector before destroying object. Used for cleanup operations.
Deprecated in newer Java versions.
86. What is Memory Leak in Java?
Answer: When objects are not being garbage collected despite being unused, usually due to
unintentional references.
87. What is Association vs Aggregation vs Composition?
Answer:
Association: General relationship between objects
Aggregation: Weak "has-a" relationship
Composition: Strong "has-a" relationship
88. What is Upcasting and Downcasting?
Answer:
Upcasting: Converting subclass reference to superclass (automatic)
Downcasting: Converting superclass reference to subclass (explicit casting required)
89. What is instanceof operator?
Answer: Tests whether an object is an instance of a specific class or interface.
90. What is ClassCastException?
Answer: Runtime exception thrown when trying to cast an object to a class of which it's not an instance.
91. What is Multiple Inheritance of Implementation vs Type?
Answer:
Implementation: Inheriting method implementations (not allowed in Java)
Type: Inheriting method signatures through interfaces (allowed in Java)
92. What is Cohesion and Coupling?
Answer:
Cohesion: How closely related elements within a module are
Coupling: How much one module depends on another
93. What are Access Modifiers in different contexts?
Answer:
Class level: public, default
Member level: public, private, protected, default
94. What is Package in Java?
Answer: Package is a namespace that organizes related classes and interfaces. Provides access control
and prevents naming conflicts.
95. What is import statement?
Answer: import allows using classes from other packages without fully qualified names.
96. What is static import?
Answer: Allows importing static members of a class so they can be used without class name qualification.
97. What is Reflection?
Answer: Reflection allows examining and modifying class structure at runtime. Can access private
members, invoke methods dynamically.
98. What is Generic Programming?
Answer: Generics provide type safety at compile time and eliminate need for typecasting. Example:
List<String> instead of raw List.
99. What is Type Erasure?
Answer: Process where generic type information is removed at runtime. Java generics are implemented
using type erasure.
100. What is Wildcard in Generics?
Answer:
? extends T: Upper bounded wildcard
? super T: Lower bounded wildcard
?: Unbounded wildcard
101. What is POCS (Plain Old Class/Object)?
Answer: Simple class with private fields, public getters/setters, no-argument constructor, and follows
JavaBean conventions.
102. What is Inner Class types?
Answer:
1. Member Inner Class: Non-static nested class
2. Static Nested Class: Static class inside another class
3. Local Inner Class: Class defined inside method
4. Anonymous Inner Class: Class without name
103. What is Lambda Expression?
Answer: Lambda expressions provide a concise way to implement functional interfaces. Introduced in
Java 8.
java
// Traditional
Runnable r1 = new Runnable(
Runnable() {
public void run(
run() {
System..out
System out..println
println(("Hello"
"Hello"));
}
};
// Lambda
System..out
Runnable r2 = () -> System out..println
println(("Hello"
"Hello"));
104. What is Method Reference?
Answer: Method reference is a shorthand notation of lambda expression to call a method.
java
// Lambda
list..forEach
list forEach((x -> System
System..out
out..println
println((x));
// Method Reference
list..forEach
list forEach((System
System..out
out::::println
println));
105. What is Stream API?
Answer: Stream API provides functional-style operations on collections. Supports operations like filter,
map, reduce.
Key Interview Tips
Common Coding Questions:
1. Implement inheritance hierarchy (Vehicle -> Car -> SportsCar)
2. Create abstract class with abstract and concrete methods
3. Demonstrate polymorphism with method overriding
4. Implement Singleton pattern
5. Show encapsulation with getter/setter
6. Create interface and implementing classes
7. Demonstrate constructor chaining
Important Points to Remember:
Always explain with examples
Mention real-world applications
Know the differences between concepts clearly
Practice coding implementations
Understand memory management aspects
Be familiar with both Java and C++ implementations
Most Asked OOPs Questions in Interviews:
1. Explain OOPs principles with examples
2. Difference between abstract class and interface
3. Method overloading vs overriding
4. Inheritance types and their use cases
5. Polymorphism implementation
6. Exception handling in inheritance
7. Design patterns implementation
This comprehensive guide covers all essential OOPs concepts that are frequently asked in technical
interviews, especially for companies like NRI Fintech!