Common OOPS Interview Questions (2023)

Why do we use Oops?

  • Oops, it stands for Object-Oriented Programming, which helps the developer easily control and access a program's data.
  • Oops, it helps developer to write code in a better way and improves code readability and reusability. 
  • Oops, it keeps our code DRY "don't repeat yourself" and makes the code easier to maintain, modify and debug.
  • It helps to create a clear structure for your application.

What are Class and Objects?

  • Class is a blueprint. Class may have field, property, method, delegate, and events. 
  • The object is an instance of the class, and using the object, you can access all class members, like field, property, method, etc.

What are Access Modifiers?

Public

Accessible by anyone like the same class, derived class, current assembly, and another assembly. Please refer below example. I have created public property with a name and then a Product Base class inherited from the product class. I have created a product class object and accessed that property in the main method. It means public property accessible by anyone in the same class, derived class, current assembly, and another assembly.

Code

Private

Access is limited to the class which contains it. If the variable declares private in a class, then accessible in that class only, the user can not access outside from that class. Please check the below example, Base class ID property is marked private, then that class is inherited in another class and then created object of that class, but the property ID is not accessible in that class.

Code

Code

Protected

When we declare a member protected, it can be accessed only within the same or derived class. It can not be accessed by the object of that class.

Code

Now let's inherit the Product class into the Program class. If we want to access a protected member, we need to create an object of the derived class, and then we can access a protected member. I have made a member name with protected access modifier and accessed it via the program class object,t as in the snippet below.

Code

Internal

Internal can be visible inside the same assembly and accessible through an object. It can not be accessible outside of assembly, either object or inheritance.

Protected Internal

Protected Internal can be visible inside the same assembly through objects and in derived classes outside the assembly through member functions.

Below is a pictorial to represent the access modifier, which helps us understand easily. Here have created a snippet that indicates which access modifier has accessibility.

Table

4. What is the main pillar of Object-Oriented Programming?

There are four main pillars of Object-oriented programming,

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

5. What are Abstraction and Encapsulation?

Abstraction

  • Abstraction means to show only what is necessary. In other words, show only necessary features without background details. 
  • Abstraction can be achieved by using access modifiers, abstract classes, and interfaces.
  • It solved a problem at the design level

Encapsulation

  • Encapsulation is the process of wrapping several items like variables, methods, and functions in a single entity, making the system easier to handle and use for the end-user.
  • Encapsulation can be achieved by using classes.

6. Inheritance

  • Inheritance is one of the most important concepts in object-oriented programming. Inheritance allows the developer to reuse the functionality of the base class and speed up development time.
  • Inheritance is the process of deriving a new class from an existing class and available all base class functionality in the derived class.

7. What is Polymorphism?

  • Polymorphism is one of the most important concepts of object-oriented programming. It describes a single name with multiple behaviors, which means a single function can be defined with different definitions.
  • There are two types of polymorphisms, one is compiled time polymorphism (Method Overloading), and another is run time polymorphism (Method Overriding)
  • We can call it another name, like static polymorphism (Method Overloading) and dynamic polymorphism (Method Overriding).

8. What is Method Overloading?

Method overloading is compiled time polymorphism. Method overloading means the method name is the same, but the parameter may differ. Let's take the example of method overloading below,

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace OOPSQuestions {
    class Program {
        static void Main(string[] args) {
            //Get All product without parameter
            var result = GetProducts();
            //Get products with price greater than 325
            var productWithPrice = GetProducts(325);
            //Get products with name contains shirt
            var productWithName = GetProducts("Shirt");
            //Get products with name start H and price greater than 325
            var productWithNameAndPrice = GetProducts("H", 325);
        }
        public static List < Product > GetProducts() {
            List < Product > products = BuildProduct();
            return products;
        }
        public static List < Product > GetProducts(decimal price) {
            List < Product > products = BuildProduct().Where(x => x.price > price).ToList();
            return products;
        }
        public static List < Product > GetProducts(string Name) {
            List < Product > products = BuildProduct().Where(x => x.Name.Contains(Name)).ToList();
            return products;
        }
        public static List < Product > GetProducts(string Name, decimal price) {
            List < Product > products = BuildProduct().Where(x => x.Name.StartsWith(Name) && x.price > price).ToList();
            return products;
        }
        public static List < Product > BuildProduct() {
            var list = new List < Product > () {
                new Product() {
                        Id = 1,
                            Name = "T Shirt",
                            Code = "PTS",
                            Description = "Polyster Tshirt",
                            price = 300
                    },
                    new Product() {
                        Id = 2,
                            Name = "Full Sleev Shirt",
                            Code = "PSS",
                            Description = "cotton Full Sleev Shirt",
                            price = 350
                    },
                    new Product() {
                        Id = 3,
                            Name = "Hoodies",
                            Code = "PHD",
                            Description = "Polyster Hoodies",
                            price = 400
                    },
                    new Product() {
                        Id = 4,
                            Name = "Half Sleev Shirt",
                            Code = "HSS",
                            Description = "Half Sleev Shirt",
                            price = 350
                    }
            };
            return list;
        }
    }
}
public class Product {
    public int Id {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }
    public string Code {
        get;
        set;
    }
    public string Description {
        get;
        set;
    }
    public decimal price {
        get;
        set;
    }
}

In the above example, I created the GetProduct() method with the same name but different parameters.

  • First method without parameter - GetProducts()
  • The second method with one parameter as decimal type - GetProducts(decimal price)
  • The third method takes string parameter - GetProducts(string Name)
  • The fourth one takes two parameters, string and decimal - GetProducts (string Name, decimal price

Note. The method's overloading parameters may differ, but the return type must be the same.

9. What is Method Overriding?

Overriding means overriding the base class method in a derived class with different logic but with the same name and same parameter. While creating the method in the base class, we need to mark a method as virtual, and in a derived class, we need to mark it with the override keyword. Let's take an example of method overriding,

public class Customer {
    public int Id {
        get;
        set;
    }
    public string FirstName {
        get;
        set;
    }
    public string LastName {
        get;
        set;
    }
    public string Email {
        get;
        set;
    }
    public virtual string GetCustomerName() {
        return FirstName + ' ' + LastName + ' ' + "Regular Customer";
    }
}
public class SalesCustomer: Customer {
    public override string GetCustomerName() {
        return FirstName + ' ' + LastName + ' ' + "Sales Customer";
    }
}
public class WholeSallerCustomer: Customer {
    public override string GetCustomerName() {
        return FirstName + ' ' + LastName + ' ' + "Wholesaler Customer";
    }
}
public class StudentCustomer: Customer {
    public override string GetCustomerName() {
        return FirstName + ' ' + LastName + ' ' + "Student Customer";
    }
}

10. What is the difference between Method Overloading and Method Overriding?
 

Method Overloading Method Overriding
Method overloading is compiled time/ Static polymorphism. Method overriding is run time/ dynamic polymorphism
Creating more than one method in the same class with different parameters and the same return type is called method overloading. Creating the same method in the base class with the Virtual keyword and child class overrides the logic for the method means method overloading. The base class method should be virtual, and the child class method should use the override keyword to redefine the method.
It does not require inheritance, which means it can implement in the same class. Method overriding requires inheritance to override a method in the derived class. It's not possible in a single class.
We can use any access modifier in method overloading. The access modifier must be public only.


11. What is the use of Virtual Keywords?

Virtual keyword is used to redefine your method and property in your child/derived class. It will allow the developer to override a method or property in a child class.

12. Can we implement Polymorphism without Inheritance?

Partially yes, compile-time polymorphism is possible without inheritance, but if we want to do dynamic or runtime polymorphism, then it requires inheritance.

13. Static vs. Dynamic Polymorphism?

  • Static/Compile time → Method overloading.
  • Dynamic/Runtime  → Method overriding

14. Why do we need an Abstract Class?

We would create an abstract class when we do not allow creating instances of a class, and we want to provide some common member with default implementation and method without implementation, which must be overridden by the respective child/derived class. In this scenario, we will create a base class as an abstract class that will be inherited in the child class and provides abstract method implementation in the child/derived class.

15. Are Abstract Methods Virtual?

  • Yes, abstract methods are virtual by definition because they must be overridden in subclasses.
  •  When a method declaration includes an abstract modifier, it means it is an abstract method. Although an abstract method is implicitly a virtual method, it cannot have the modifier virtual.

16. Can we create an instance of an Abstract Class?

No, we can not create an instance of an abstract class. We need to create an instance of the child class to access all members.

17. Is it compulsory to implement an Abstract Class?

If you are inheriting an abstract class in the child class, then it's mandatory to implement all abstract methods of an abstract class.

18 What is the difference between Abstract Class and Interface?

  Abstract Class  Interface
Declaration Keyword  Abstract keyword is used to create an abstract class The interface keyword is used to create an interface
Constructor An abstract class can have a constructor An interface can not have the constructor
Static Members An abstract class can contain static members There are no static members in the interface
Default Implementation An abstract class can have a default implementation for methods An interface can not have default implementation before C# 8. Method declaration only allowed in interface.(C# 8 support default implementation)
Can have Fields  In abstract class, we can have fields Interface can't have fields
Access Modifier Abstract we can use the access modifier We can not use an access modifier in the interface, even if you can not give public access modifier.
Default Access modifier Abstract class members are private by default Interface members are public by default
Inheritance An abstract class can inherit class and Interface Only interface can inherit interface; It can not inherit Abstract or normal class.
Method An abstract class can have abstract and not abstract methods. It can be fully, partially, or non-implemented. The interface has only abstract methods means no implemented methods. (Before c# 8). C# 8 can have a default implementation for the method.

19. Why do we need an Interface?

  • C# not supporting multiple inheritances by default. So if you want multiple inheritances, you can achieve this by interface but not by classes.
  • Advantage of Interface
    • Create a loosely coupled system with the help of an Interface
    • The interface allows the developer to plug and play method.
    • Complete abstraction is allowed by the implementation of the interface.
    • Interfaces are very useful in dependency injection.
    • The interface helps developers to unit test and mocking easier.

20. What is Explicit Interface mplementation?

Explicit interface implementation means if you have two interfaces with the same method name and want to provide different implementations for both interface methods, then you can implement the explicit interface. Let's take an example.

class Program {
    static int count = 0;
    static void Main(string[] args) {
        ExplicitInterface explicitInterface = new ExplicitInterface();
        ((IInterface) explicitInterface).InterfaceMethod();
        ((IInterface1) explicitInterface).InterfaceMethod();
        Console.ReadLine();
    }
}

namespace OOPSQuestions.Interfaces {
    public interface IInterface {
        void InterfaceMethod();
    }
    public interface IInterface1 {
        void InterfaceMethod();
    }
    public class ExplicitInterface: IInterface, IInterface1 {
        public void InterfaceMethod() {
            Console.WriteLine("IInterface Method Called");
        }
    }
}

The output of the above code snippet is as below,

If you run the above program still, both interfaces will call the same method. Still, if you have a different interface reference to your class and call that method, then the same method call will make ambiguity.

Now, let's implement an interface explicitly using the interface name. One thing to note is that when you are explicit implementation, access modifiers are not allowed for those members. Please refer below to an example of explicit interface implementation.

public class ExplicitInterface: IInterface, IInterface1 {
    void IInterface.InterfaceMethod() {
        Console.WriteLine("IInterface Method Called");
    }
    void IInterface1.InterfaceMethod() {
        Console.WriteLine("IInterface1 Method Called");
    }
}


public class Program {
    static int count = 0;
    static void Main(string[] args) {
        ExplicitInterface explicitInterface = new ExplicitInterface();
        ((IInterface) explicitInterface).InterfaceMethod();
        ((IInterface1) explicitInterface).InterfaceMethod();
        Console.ReadLine();
    }
}

The output of the above code snippet is below; you can call the respective interface method using Typecast.

Another way of call the method of the explicit interface,

Public class Program {
    static void Main(string[] args) {
        IInterface i = new ExplicitInterface();
        i.InterfaceMethod();
        IInterface1 i1 = new ExplicitInterface();
        i1.InterfaceMethod();
        Console.ReadLine();
    }
}

21. Can we write the logic in the Interface?

No, we can not write logic inside the interface method (Before C# 8). The interface can have only a method signature without any implementation.

22. Can we declare the property in the Interface?

Yes, We can create properties in the interface, but they can not contain a field.

23. Can we use an access modifier for the Interface method?

No, we can not have an access modifier in the interface method.

24. Can we create an instance of an Interface?

No, We can not create an instance of an interface. Inherited classes need to implement an interface method, and using that class object, we can use that method.

25. Interface Segregation Principle?

  • Interface contracts, By having a contract, we have better control over impact analysis, change management, and breaking changes.
  • Multiple inheritances help us to add new methods without affecting the old interfaces.

Summary

In this article, I have covered most of the OOPS interview questions which may ask of Microsoft .net developers. This set of questions will help fresh developers and intermediate developers to answer interview questions with confidence. If you answer OOPS questions with confidence, then chances are more of getting selected for an interview which will help you to get confidence. I am planning to cover other interview questions in my upcoming article. 


Recommended Free Ebook
Similar Articles