Home » Interview Questions Answers » 43 Must-known OOPs Interview Questions & Answers

43 Must-known OOPs Interview Questions & Answers


OOPs Interview Questions and Answers

Here are the top 43 OOPs interview questions and answers for beginners and professionals.

Other Interview Questions – C#, SQL


OOPs Interview Questions And Answers

Download all Questions as .PDF




What is OOPs?

Object-Oriented Programming (OOP) is a way of writing programs using “objects,” which are like building blocks. Each object can hold data (attributes) and actions (methods) that work on the data. It makes easier to manage complex programs by breaking them into smaller, reusable parts.

The main principles of OOPs areEncapsulation, Abstraction, Inheritance, Polymorphism.




What is Class?

A class is a blueprint for creating objects. It defines the attributes (data) and methods (actions) that the objects created from the class will have. Classes help organize and structure code by grouping related data and functions together.





What is Object?

An object is a self-contained unit that holds both data and actions. The data is called attributes, and the actions are called methods. Objects are like real-world things with properties and behaviors.





What is the difference between a Class and an Object?


Class Object
Definition A blueprint or template for creating objects An instance of a class
Purpose Defines properties (attributes) and methods (behavior) Represents a specific entity with actual values
Creation Defined using the class keyword Created using the new keyword
Memory Does not occupy memory until an object is created Occupies memory when it is instantiated
Example class Person { public string Name; public int Age; } Person person = new Person();
Data Contains no data, only definitions Contains actual data and state
Lifecycle Exists as long as the program is running (static context) Exists as long as it is referenced (dynamic context)



What is Encapsulation?

Encapsulation means that a group of related properties, methods, and other memebers are treated as a single unit or object. It helps protect the data by restricting direct access from outside the object, allowing it to be accessed or modified only through defined methods. This is achieved by using access modifiers like private, public, protected, internal.





What is Abstraction?

Abstration means hiding the unnecessary details and showing only the essential features of an object.

In C#, we can implement the abstraction OOPs principle in two ways:

  1. Using Interface
  2. Using Abstract Classes and Abstract Methods




Difference between Encapsulation and Abstraction


Encapsulation Abstraction
Encapsulation hides the internal state of an object and requires all interaction to be performed through an object's methods. Abstraction hides complex implementation details and shows only the necessary features of an object.
Achieved by using access modifiers (private, protected, public). Achieved by using abstract classes and interfaces.
Focuses on restricting access to data. Focuses on hiding the complexity of the system.
Ensures that the object's internal state cannot be directly accessed. Provides a high-level view of an object's functionality.



What is Inheritance?

Inheritance allows a new class to inherit properties and methods from an existing class. This promotes code reusability and establishes a relationship between classes. The class that is inherited from is called the base class (or parent class), and the class that inherits is called the derived class (or child class).





What is Polymorphism?

Polymorphism allows a method to be defined in multiple ways in a class, enabling it to behave differently based on the object that invokes it.

Method overloading is achieved in three ways:

  • Different number of parameters
  • Different types of parameters
  • Different order of parameters

Types of Polymorphism:

  1. Compile-time Polymorphism: Also called as Static Polymorphism/ Method Overloading/ Early Binding. It Allows multiple methods in the same class to have the same name but different parameters. Achieved through method overloading and operator overloading.


  2. Run-time Polymorphism: Also called as Dynamic Polymorphism/ Method Overriding/ Late Binding. It Allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Achieved through method overriding, typically using inheritance and interfaces.



Can method overloading have different return type in C#?

If both methods have the same parameter types, but different return type, then it is not possible. you cannot declare two methods with the same signature and different return type.

Method overloading primarily depends on having different parameter lists (different number or types of parameters). The parameter lists must differ, then you can have method overloading with different return type, see the below example.





Can static methods be overloaded in C#?

Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.




Can return type be different in method overriding C#?

An override method must have the same signature as the overridden base method. override methods support covariant return types. In particular, the return type of an override method can derive from the return type of the corresponding base method.

You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

You cannot use the new, static, or virtual modifiers to modify an override method.




What is an Abstract class?

An abstract class is a class that cannot be instantiated and is meant to be inherited by other classes. It can contain abstract methods (without implementation) and regular methods (with implementation).





Can I declare an abstract class without defining an abstract method in it?

Yes, you can have an abstract class without any abstract methods. An abstract class can contain only regular methods (with implementation), properties, fields, and other members. The purpose of an abstract class in such cases is to prevent instantiation of the class directly and to provide a common base for derived classes.




What is an Abstract method?

An abstract method is a method that is declared in an abstract class but does not have an implementation in that class.

  • Abstract methods contain only the method signature (name, return type, parameters) without any body.
  • They can only be declared in abstract classes.
  • Any non-abstract class inheriting an abstract class must implement all its abstract methods, ensuring that they provide specific functionality.
  • Abstract classes, and therefore their abstract methods, cannot be instantiated directly.



Can I declare “abstract method” in a “non-abstract class”?

No, you cannot declare an abstract method in a non-abstract class. Abstract methods can only be declared in abstract classes. This is because an abstract method does not have an implementation, and a non-abstract class is expected to be instantiable and provide full implementations for all its methods.




What is Interface?

An interface class is a blueprint for classes that defines methods and properties but does not provide their implementation. Classes that implement the interface must provide the implementation for all its members.





Can Interface have accessibility modifier?

All elements in the Interface should be public. Therefore, by default, all interface elements are public by default.




Can a class implement multiple Interfaces?

Yes, a class can implement multiple interfaces. This allows a class to inherit behaviors and contracts from more than one interface.





Difference between Abstract and Interface.


Abstract Class Interface
Keyword abstract interface
Methods Can have both abstract (without implementation) and regular (with implementation) methods Can only have methods without implementation (default methods with implementations are allowed from C# 8.0)
Fields Can have fields (variables) Cannot have fields
Properties Can have properties with or without implementation Can have properties but no implementation
Constructors Can have constructors Cannot have constructors
Inheritance Can inherit from only one base class Can inherit from multiple interfaces
Access Modifiers Can use access modifiers (public, protected, private) Members are public by default, no access modifiers allowed
Usage Used when classes share a common base with some shared implementation Used to define a contract that multiple classes can implement
Instantiation Cannot be instantiated directly Cannot be instantiated directly



What is a Constructor?

A constructor is a special method in a class that is automatically called when an object of the class is created. It is used to initialize the object’s properties.

A constructor must have the same name as the class and cannot have a return type, not even void.





Can I have multiple Constructors in a Class?

Yes, you can have multiple constructors in a class. This is known as constructor overloading, where each constructor has a different parameter list (different number or types of parameters).





What is the purpose of a constructor?

The purpose of a constructor is to initialize a new object of a class.

Key Points:

  • Initialization: Sets initial values for the object’s properties.
  • Setup: Performs any necessary setup tasks for the object.
  • No Return Type: Constructors do not have a return type, not even void.
  • Same Name as Class: Constructors must have the same name as the class.



What are the types of constructors in OOP?

There are several types of constructors – Default, Parameterized, Copy, Static, Private:

  1. Default Constructor: A constructor that takes no parameters. It initializes objects with default values.
  2. Parameterized Constructor: A constructor that takes parameters to initialize objects with specific values.
  3. Copy Constructor: A constructor that creates a new object as a copy of an existing object. C# does not have a built-in copy constructor, but you can implement one.
  4. Static Constructor: A constructor used to initialize static members of the class. It is called once, before any instance of the class is created or any static member is accessed.
  5. Private Constructor: A constructor that cannot be accessed outside its class. It is used to prevent the creation of instances from outside the class, often used in singleton pattern.




Can constructors be overloaded?

Yes





What is the difference between a constructor and a method?


Constructor Method
Purpose Initializes a new object Performs an action or calculates a value
Name Same name as the class Can have any name
Return Type No return type, not even void Must have a return type, or void if no value is returned
Call Automatically called when an object is created Explicitly called using the object reference
Overloading Can be overloaded Can be overloaded
Inheritance Not inherited by derived classes, but can be called explicitly Inherited by derived classes
Usage Sets up initial state of an object Defines behaviors and functionalities



What is Destructor in OOPs?

A destructor in Object-Oriented Programming (OOP) is a special member function of a class that is executed when an object of that class is destroyed. Destructors are used to perform any necessary final clean-up when an object is no longer needed, such as releasing resources like memory, file handles, or network connections and to perform any finalization steps required before the object is destroyed.

In C#, destructors are defined using a tilde (~) followed by the class name. The .NET garbage collector automatically calls the destructor before reclaiming the memory used by an object.

Note: Using IDisposable and using is often a better practice for resource management in C#.





What is the significance of the super keyword in inheritance?

The super keyword is significant in inheritance because it allows a derived class to access and invoke methods, properties, and constructors of its base class. This is particularly important for ensuring proper initialization and extending or modifying the behavior of base class methods in derived classes.

Although C# does not have a super keyword, the base keyword serves the same purpose.





Explain the “this” keyword.

The ‘this’ keyword refers to the current instance of the class in which it is used and provides a way to reference the current object.

Key Uses of this Keyword:

  1. Distinguishing Between Instance Variables and Parameters: When a parameter or a local variable has the same name as an instance variable, this can be used to refer to the instance variable.
  2. Calling Other Constructors: It can be used to call another constructor in the same class.
  3. Passing the Current Instance: It can be used to pass the current object as a parameter to other methods.
  4. Returning the Current Instance: It can be used to return the current object from a method.




What are Data Types?

defines the structure, behavior, and capabilities of data, specifying the operations that can be performed and how the data is stored.

Different Kind of “Types” – Value Type, Reference Type, User-Defined Type, Abstract Type, Primitive Type, Composite Type.

  1. Value Types: Types that store actual data directly. Examples: int, float, struct in C#.

  2. Reference Types: Types that store references (addresses) to the actual data rather than the data itself. Examples: Classes, arrays, strings in C#.

  3. User-Defined Types: Types that are defined by the user using the language’s class and struct mechanisms. Examples: Custom classes and structs.
  4. Abstract Types: Types that cannot be instantiated directly and are meant to be inherited by other classes. Examples: Abstract classes and interfaces.
  5. Primitive Types: Basic data types provided by a programming language. Examples: int, char, float, double, boolean in languages like Java and C#.
  6. Composite Types: Also known as complex types, they are composed of multiple primitive types. Examples: Arrays, structures, and classes.



Difference between “Class” and “Struct” in OOPs.


Class Struct (Structure)
Reference type Value type
Allocated on the heap Allocated on the stack
Has a default constructor No default constructor
Supports inheritance Does not support inheritance
Can implement interfaces Can implement interfaces
Can have abstract members Cannot have abstract members
Can be null Cannot be null (unless using nullable types)
Generally slower to access due to heap allocation Generally faster to access due to stack allocation
Used for complex data structures and behavior Used for small, simple data structures



What are Access modifiers/ specifiers?

Access modifiers/ specifiers are keywords to define the visibility and accessibility of classes, methods, and other members. They control how the members of a class can be accessed from other parts of the code.

Access ModifiersPublic, Private, Protected, Internal, Protected Internal, Private Protected

  1. Public: Members declared as public are accessible from any other code in the same assembly or another assembly that references it.


  2. Private: Members declared as private are accessible only within the same class or struct.


  3. Protected: Members declared as protected are accessible within the same class and by derived class instances.


  4. Internal: Members declared as internal are accessible only within the same assembly, but not from another assembly.


  5. Protected Internal: Members declared as protected internal are accessible within the same assembly or from derived classes in other assemblies.


  6. Private Protected: Members declared as private protected are accessible within the same class and derived classes within the same assembly.



What is the ‘override’ keyword used for?

The override keyword in C# is used for the following purposes:

  • Extending or Modifying Base Class Methods: Allows a derived class to provide a specific implementation of a method that is already defined in its base class.
  • Implementing Polymorphism: Enables runtime polymorphism, allowing the derived class method to be called through a base class reference.
  • Overriding Virtual/Abstract Methods: Used to override methods marked as virtual, abstract, or override in the base class.
  • Ensuring Derived Class Method Execution: Guarantees that the derived class’s version of the method is executed, even when called through a base class reference.
  • Providing Specific Functionality: Allows derived classes to implement or modify behavior specific to their needs, providing more tailored functionality.




Can I override a method that is marked as ‘override’ in a base class?

Yes





What is Sealed Class and Sealed methods in OOPs

A sealed class and sealed methods are used to restrict inheritance and prevent further derivation or overriding. This can be useful for ensuring that a class or method’s behavior remains unchanged. This is done by sealed keyword.

1) Sealed Class – A sealed class is a class that cannot be inherited by any other class. This means you cannot create a subclass of a sealed class. It is used to prevent further inheritance and to secure the implementation of a class.



2) Sealed Method – A sealed method is a method in a derived class that overrides a method in a base class but cannot be further overridden by any classes that derive from the derived class.





Difference between a Sealed class and a Sealed method


Sealed Class Sealed Method
A class that cannot be inherited A method that cannot be overridden in derived classes
Prevents inheritance and ensures no class can derive from it Prevents further overriding of a method in derived classes
public sealed class MyClass { } 
public sealed override void MyMethod() { } 
Used when you want to restrict class inheritance Used in a derived class to prevent further method overriding
Inheriting from a sealed class causes a compile-time error Overriding a sealed method in a derived class causes a compile-time error



Difference between an Abstract method & Virtual method


Abstract Method Virtual Method
Declaration Declared with the abstract keyword in an abstract class Declared with the virtual keyword
Implementation No implementation in the base class Can have an implementation in the base class
Class Requirement Must be in an abstract class Can be in any class (abstract or concrete)
Overriding Must be overridden in derived non-abstract classes Can be optionally overridden in derived classes
Instantiation Cannot instantiate the class directly (must be abstract) Can instantiate the class directly
Modifier Requirement Must be abstract (no other modifiers like static, sealed) Can be combined with other modifiers (sealed, override)
Purpose To force derived classes to provide a specific implementation To provide a default implementation that derived classes can override



What is the role of an Accessor and a Mutator in OOP?

Accessors and Mutators are methods used to access and modify the private fields of a class. These methods are often referred to as “getters” and “setters.”

Accessors (Getters) – used to read the value of a private field.

Mutators (Setters) – used to modify the value of a private field.





What is reflection in OOP?

Reflection allows you to obtain information about assemblies, modules, types, and members (fields, properties, methods, etc.) at runtime. This includes examining metadata about types, accessing type information, and dynamically invoking methods or accessing properties.





Which of these terms defines the hiding of an object’s details from the other program?

Select from the following answers:
a) Encapsulation
b) Abstraction
c) member hiding
d) None

Answer: (a) Encapsulation




what do you mean by ‘implicit’ and ‘explicit’?

Implicit means something happens automatically without the programmer needing to specify it directly. In type conversion, an implicit conversion occurs when a value of one type is automatically converted to another type by the compiler, without needing an explicit cast by the programmer.

int intNumber = 42;
// Implicit conversion from int to double
double doubleNumber = intNumber; 

Explicit means something is done deliberately and requires specific instructions from the programmer. In type conversion, an explicit conversion requires the programmer to use a cast or a specific method to convert a value from one type to another. This is often necessary when there is a potential for data loss or when converting between incompatible types.

double doubleNumber = 42.5;
// Explicit conversion from double to int
int intNumber = (int)doubleNumber; 



Explain the ‘concept of reusability’ in OOP.

Reusability in OOP refers to the ability to use existing code components in new applications or different parts of the same application. This is achieved through several key OOP concepts, including inheritance, polymorphism, and encapsulation, which help in writing modular, maintainable, and scalable code.

Benefits of Reusability:

  1. Reduced Development Time: Reusing existing components reduces the time required to develop new features or applications.
  2. Increased Reliability: Reused code components are likely to be well-tested and proven in other applications, leading to more reliable software.
  3. Consistency: Using the same components across different parts of an application or different projects ensures consistent behavior and interface.
  4. Maintainability: Changes and bug fixes can be made in one place and automatically propagated to all instances where the component is used.



How do you test OOP code?


Approaches to Testing OOP Code:

  • Unit Testing: Focuses on testing individual units (e.g., methods, classes) in isolation.
  • Integration Testing: Tests the interactions between different classes and modules. Ensures that combined components work together as expected.
  • System Testing: Tests the entire system as a whole. Ensures that the complete application functions as intended.
  • Mocking: Replaces real objects with mock objects to isolate the unit of code being tested. Useful for testing classes that depend on external resources or other classes.

Tools for Testing OOP Code:

  • Unit Testing Frameworks like NUnit, xUnit.
  • Mocking Frameworks like Moq

Steps to Test OOP Code:

  • Write Test Cases: Identify the methods and classes to be tested. Write test cases that cover different scenarios, including edge cases and error conditions.
  • Use Assertions: Verify that the actual output matches the expected output using assertions. Common assertion methods include Assert.AreEqual, Assert.IsTrue, Assert.Throws, etc.
  • Setup and Teardown: Initialize any necessary objects or state before each test (Setup). Clean up after each test to ensure tests are independent and repeatable (Teardown).
  • Mock Dependencies: Use mocking frameworks to create mock objects for any dependencies. Inject mock objects into the class under test to isolate its behavior.
  • Run Tests: Execute the tests using a test runner or IDE integration. Review the results and fix any failing tests.



Download all Questions as .PDF


loading…

Leave a Reply

Your email address will not be published. Required fields are marked *