40+ OOP Interview Questions in 2019

Alex πŸ‘¨πŸΌβ€πŸ’»FullStack.Cafe - Dec 10 '18 - - Dev Community

40 C# Object-Oriented Programming Interview Questions in 2019
OOP is, by far, the most common programming paradigm used in the IT industry. All the major programming languages now support OOP including C#. OOP reflects the real world behavior of how things work and the most efficient way to model and organize very large applications.

Originally published on FullStack.Cafe - Never Fail Your Tech Interview Again

Q1: What is inheritance?

Topic: OOP
Difficulty: ⭐

Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

πŸ”— Source: tutorialspoint.com

Q2: What is object-oriented programming (OOP)?

Topic: OOP
Difficulty: ⭐

OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object is created in the program to represent a class. Therefore, an object encapsulates all the features, such as data and behavior that are associated to a class. OOP allows developers to develop modular programs and assemble them as software. Objects are used to access data and behaviors of different software modules, such as classes, namespaces, and sharable assemblies. .NET Framework supports only OOP languages, such as Visual Basic .NET, Visual C#, and Visual C++.

πŸ”— Source: indiabix.com

Q3: What is encapsulation?

Topic: OOP
Difficulty: ⭐⭐

Encapsulation is defined as the process of enclosing one or more items within a physical or logical package. Encapsulation, in object oriented programming methodology, prevents access to implementation details.

πŸ”— Source: tutorialspoint.com

Q4: What is polymorphism?

Topic: OOP
Difficulty: ⭐⭐

The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as one interface, multiple functions.

πŸ”— Source: tutorialspoint.com

Q5: What is the difference between procedural and object-oriented programming?

Topic: OOP
Difficulty: ⭐⭐

Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.

πŸ”— Source: indiabix.com

Q6: Explain the concept of constructor?

Topic: OOP
Difficulty: ⭐⭐

Constructor is a special method of a class, which is called automatically when the instance of a class is created. It is created with the same name as the class and initializes all class members, whenever you access the class. The main features of a constructor are as follows:

  • Constructors do not have any return type.
  • Constructors can be overloaded.
  • It is not mandatory to declare a constructor; it is invoked automatically by .NET Framework.

πŸ”— Source: indiabix.com

Q7: Why is the virtual keyword used in code?

Topic: OOP
Difficulty: ⭐⭐

The virtual keyword is used while defining a class to specify that the methods and the properties of that class can be overridden in derived classes.

πŸ”— Source: indiabix.com

Q8: What is the difference between a class and a structure?

Topic: OOP
Difficulty: ⭐⭐

Class:

  • A class is a reference type.
  • While instantiating a class, CLR allocates memory for its instance in heap.
  • Classes support inheritance.
  • Variables of a class can be assigned as null.
  • Class can contain constructor/destructor.

Structure:

  • A structure is a value type.
  • In structure, memory is allocated on stack.
  • Structures do not support inheritance.
  • Structure members cannot have null values.
  • Structure does not require constructor/destructor and members can be initialiazed automatically.

πŸ”— Source: indiabix.com

Q9: What is the relationship between a class and an object?

Topic: OOP
Difficulty: ⭐⭐

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the class. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

πŸ”— Source: indiabix.com

Q10: When should I use a struct instead of a class?

Topic: OOP
Difficulty: ⭐⭐⭐

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

πŸ”— Source: stackoverflow.com

Q11: What is polymorphism, what is it for, and how is it used?

Topic: OOP
Difficulty: ⭐⭐⭐

Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button β€œdoes,” however, depends on what it is connected to and the context in which it is used β€” but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

πŸ”— Source: stackoverflow.com

Q12: What do you mean by data encapsulation?

Topic: OOP
Difficulty: ⭐⭐⭐

Data encapsulation is a concept of binding data and code in single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access of data and restricts the user to use the necessary data only.

πŸ”— Source: indiabix.com

Q13: What are abstract classes? What are the distinct characteristics of an abstract class?

Topic: OOP
Difficulty: ⭐⭐⭐

An abstract class is a class that cannot be instantiated and is always used as a base class.

The following are the characteristics of an abstract class:

  • You cannot instantiate an abstract class directly. This implies that you cannot create an object of the abstract class; it must be inherited.
  • You can have abstract as well as non-abstract members in an abstract class.
  • You must declare at least one abstract method in the abstract class.
  • An abstract class is always public.
  • An abstract class is declared using the abstract keyword.

The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

πŸ”— Source: indiabix.com

Q14: What are similarities between a class and a structure?

Topic: OOP
Difficulty: ⭐⭐⭐

The following are some of the similarities between a class and a structure:

  • Access specifiers, such as public, private, and protected, are identically used in structures and classes to restrict the access of their data and methods outside their body.
  • The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Both structures and classes can implement interfaces to use multiple-inheritance in code.
  • Both structures and classes can have constructors with parameter.
  • Both structures and classes can have delegates and events.

πŸ”— Source: indiabix.com

Q15: How can you prevent a class from overriding in C#?

Topic: OOP
Difficulty: ⭐⭐⭐

You can prevent a class from overriding in C# by using the sealed keyword.

πŸ”— Source: indiabix.com

Q16: How is method overriding different from method overloading?

Topic: OOP
Difficulty: ⭐⭐⭐

  • Overriding involves the creation of two or more methods with the same name and same signature in different classes (one of them should be parent class and other should be child).
  • Overloading is a concept of using a method at different places with same name and different signatures within the same class.

πŸ”— Source: indiabix.com

Q17: Can you specify the accessibility modifier for methods inside the interface?

Topic: OOP
Difficulty: ⭐⭐⭐

All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

πŸ”— Source: indiabix.com

Q18: Is it possible for a class to inherit the constructor of its base class?

Topic: OOP
Difficulty: ⭐⭐⭐

No, a class cannot inherit the constructor of its base class.

πŸ”— Source: indiabix.com

Q19: What is the difference between cohesion and coupling?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

  • Cohesion refers to what the class (or module) can do.

    • Low cohesion would mean that the class does a great variety of actions - it is broad, unfocused on what it should do.
    • High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.
  • As for coupling, it refers to how related or dependent two classes/modules are toward each other. For low coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.

Good software design has high cohesion and low coupling.

πŸ”— Source: stackoverflow.com

Q20: What's the advantage of using getters and setters - that only get and set - instead of simply using public fields for those variables?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.

Here are the some of the reasons I am aware of:

  • Encapsulation of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
  • Hiding the internal representation of the property while exposing a property using an alternative representation.
  • Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
  • Controlling the lifetime and memory management (disposal) semantics of the property - particularly important in non-managed memory environments (like C++ or Objective-C).
  • Providing a debugging interception point for when a property changes at runtime - debugging when and where a property changed to a particular value can be quite difficult without this in some languages.
  • Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, and WPF come to mind.
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
  • Allowing the getter/setter to be passed around as lambda expressions rather than values.
  • Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.

πŸ”— Source: stackoverflow.com

Q21: What exactly is the difference between an interface and abstract class?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

  • An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way". An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.
  • Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

πŸ”— Source: stackoverflow.com

Q22: What is Coupling in OOP?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

OOP Modules are dependent on each other. Coupling refers to level of dependency between two software modules. Two modules are highly dependent on each other if you have changed in one module and for supporting that change every time you have to change in dependent module. Loose Coupling is always preferred. Inversion of Control and dependency injections are some techniques for getting loose coupling in modules.

πŸ”— Source: dotnetpattern.com

Q23: What is Cohesion in OOP?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

In OOP we develop our code in modules. Each module has certain responsibilities. Cohesion shows how much module responsibilities are strongly related. Higher cohesion is always preferred. Higher cohesion benefits are:

  • Improves maintenance of modules
  • Increase reusability

πŸ”— Source: dotnetpattern.com

Q24: Explain the concept of destructor?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

A destructor is a special method for a class and is invoked automatically when an object is finally destroyed. The name of the destructor is also same as that of the class but is followed by a prefix tilde (~).

A destructor is used to free the dynamic allocated memory and release the resources. You can, however, implement a custom method that allows you to control object destruction by calling the destructor.

The main features of a destructor are as follows:

  • Destructors do not have any return type
  • Similar to constructors, destructors are also always public
  • Destructors cannot be overloaded.

πŸ”— Source: indiabix.com

Q25: Differentiate between an abstract class and an interface.

Topic: OOP
Difficulty: ⭐⭐⭐⭐

Abstract Class:

  1. A class can extend only one abstract class
  2. The members of abstract class can be private as well as protected.
  3. Abstract classes should have subclasses
  4. Any class can extend an abstract class.
  5. Methods in abstract class can be abstract as well as concrete.
  6. There can be a constructor for abstract class.
  7. The class extending the abstract class may or may not implement any of its method.
  8. An abstract class can implement methods.

Interface

  1. A class can implement several interfaces
  2. An interface can only have public members.
  3. Interfaces must have implementations by classes
  4. Only an interface can extend another interface.
  5. All methods in an interface should be abstract
  6. Interface does not have constructor.
  7. All methods of interface need to be implemented by a class implementing that interface.
  8. Interfaces cannot contain body of any of its method.

πŸ”— Source: indiabix.com

Q26: What is a static constructor?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:

  • No access specifier is required to define it.
  • You cannot pass parameters in static constructor.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once, when the program execution begins.

πŸ”— Source: indiabix.com

Q27: Explain different types of inheritance.

Topic: OOP
Difficulty: ⭐⭐⭐⭐

Inheritance in OOP is of four types:

  • Single inheritance - Contains one base class and one derived class
  • Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
  • Multilevel inheritance - Contains a class derived from a derived class
  • Multiple inheritance - Contains several base classes and a derived class

All .NET languages supports single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces.

πŸ”— Source: indiabix.com

Q28: Does .NET support multiple inheritance?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

.NET does not support multiple inheritance directly because in .NET, a class cannot inherit from more than one class. .NET supports multiple inheritance through interfaces.

πŸ”— Source: indiabix.com

Q29: Can you declare an overridden method to be static if the original method is not static?

Topic: OOP
Difficulty: ⭐⭐⭐⭐

No. Two virtual methods must have the same signature.

πŸ”— Source: indiabix.com

Q30: Why Doesn't C# Allow Static Methods to Implement an Interface?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.

You pass an interface to someone, they need to know how to call a method. An interface is just a virtual method table (vtable). Your static class doesn't have that. The caller wouldn't know how to call a method. (Before i read this answer i thought C# was just being pedantic. Now i realize it's a technical limitation, imposed by what an interface is). Other people will talk down to you about how it's a bad design. It's not a bad design - it's a technical limitation.

πŸ”— Source: stackoverflow.com

Q31: What is the difference between a mixin and inheritance?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

A mix-in is a base class you can inherit from to provide additional functionality. The name "mix-in" indicates it is intended to be mixed in with other code. As such, the inference is that you would not instantiate the mix-in class on its own. Frequently the mix-in is used with other base classes. Therefore **mixins are a subset, or special case, of inheritance`88.

The advantages of using a mix-in over single inheritance are that you can write code for the functionality one time, and then use the same functionality in multiple different classes. The disadvantage is that you may need to look for that functionality in other places than where it is used, so it is good to mitigate that disadvantage by keeping it close by.

πŸ”— Source: stackoverflow.com

Q32: In terms that an OOP programmer would understand (without any functional programming background), what is a monad?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

A monad is an "amplifier" of types that obeys certain rules and which has certain operations provided.

First, what is an "amplifier of types"? By that I mean some system which lets you take a type and turn it into a more special type. For example, in C# consider Nullable<T>. This is an amplifier of types. It lets you take a type, say int, and add a new capability to that type, namely, that now it can be null when it couldn't before.

As a second example, consider IEnumerable<T>. It is an amplifier of types. It lets you take a type, say, string, and add a new capability to that type, namely, that you can now make a sequence of strings out of any number of single strings.

πŸ”— Source: stackoverflow.com

Q33: What is LSP (Liskov Substitution Principle) and what are some examples of its use (good and bad)?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

The Liskov Substitution Principle (LSP, lsp) is a concept in Object Oriented Programming that states:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. IN other words substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S.

Consider the bad example:

csharp
public class Bird{
public void fly(){}
}
public class Duck extends Bird{}
public class Ostrich extends Bird{}

The duck can fly because of it is a bird. Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it can't use the fly method, that means that we are breaking LSP principle.

So the right example:

csharp
public class Bird{
}
public class FlyingBirds extends Bird{
public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}

πŸ”— Source: stackoverflow.com

Q34: Could you elaborate Polymorphism vs Overriding vs Overloading?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

  • Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in .NET all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.

  • An override is a type of function which occurs in a class which inherits from another class. An override function "replaces" a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. Referring to the previous example, you could define your own class and override the toString() function. Because this function is inherited from Object, it will still be available if you copy an instance of this class into an Object-type variable. Normally, if you call toString() on your class while it is pretending to be an Object, the version of toString which will actually fire is the one defined on Object itself. However, because the function is an override, the definition of toString() from your class is used even when the class instance's true type is hidden behind polymorphism.

  • Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism.

πŸ”— Source: stackoverflow.com

Q35: What does it mean to β€œprogram to an interface”?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn't even an OOP concept. It means just interact with an object or system's public interface. Don't worry or even anticipate how it does what it does internally. Don't worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes.

And with databases it means using views and stored procedures instead of direct table access.

Using interfaces is a key factor in making your code easily testable in addition to removing unnecessary couplings between your classes. By creating an interface that defines the operations on your class, you allow classes that want to use that functionality the ability to use it without depending on your implementing class directly. If later on you decide to change and use a different implementation, you need only change the part of the code where the implementation is instantiated. The rest of the code need not change because it depends on the interface, not the implementing class.

This is very useful in creating unit tests. In the class under test you have it depend on the interface and inject an instance of the interface into the class (or a factory that allows it to build instances of the interface as needed) via the constructor or a property settor. The class uses the provided (or created) interface in its methods. When you go to write your tests, you can mock or fake the interface and provide an interface that responds with data configured in your unit test. You can do this because your class under test deals only with the interface, not your concrete implementation. Any class implementing the interface, including your mock or fake class, will do.

πŸ”— Source: stackoverflow.com

Q36: Can you provide a simple explanation of methods vs. functions in OOP context?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that

πŸ”— Source: stackoverflow.com

Q37: Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

Think of containment as a has a relationship. A car "has an" engine, a person "has a" name, etc. Think of inheritance as an is a relationship. A car "is a" vehicle, a person "is a" mammal, etc.

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

My acid test for the above is:

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.

e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.

  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.

e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.

πŸ”— Source: stackoverflow.com

Q38: What is the difference between association, aggregation and composition?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

  • Association is a relationship where all objects have their own lifecycle and there is no owner.

Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.

  • Aggregation is a specialised form of Association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object.

Let's take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department, the teacher object will not be destroyed. We can think about it as a β€œhas-a” relationship.

  • Composition is again specialised form of Aggregation and we can call this as a β€œdeath” relationship. It is a strong type of Aggregation. Child object does not have its lifecycle and if parent object is deleted, all child objects will also be deleted.

Let's take again an example of relationship between House and Rooms. House can contain multiple rooms - there is no independent life of room and any room can not belong to two different houses. If we delete the house - room will automatically be deleted.

Let's take another example relationship between Questions and Options. Single questions can have multiple options and option can not belong to multiple questions. If we delete the questions, options will automatically be deleted.

πŸ”— Source: stackoverflow.com

Q39: Can you declare a private class in a namespace?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private, protected, or protected internal.

πŸ”— Source: indiabix.com

Q40: You have defined a destructor in a class that you have developed by using the C# programming language, but the destructor never executed. Why did the destructor not execute?

Topic: OOP
Difficulty: ⭐⭐⭐⭐⭐

The runtime environment automatically invokes the destructor of a class to release the resources that are occupied by variables and methods of an object. However, in C#, programmers cannot control the timing for invoking destructors, as Garbage Collector is only responsible for releasing the resources used by an object. Garbage Collector automatically gets information about unreferenced objects from .NET's runtime environment and then invokes the Finalize() method.

Although, it is not preferable to force Garbage Collector to perform garbage collection and retrieve all inaccessible memory, programmers can use the Collect() method of the Garbage Collector class to forcefully execute Garbage Collector.

πŸ”— Source: indiabix.com

Thanks πŸ™Œ for reading and good luck on your interview!
Please share this article with your fellow devs if you like it!
Check more FullStack Interview Questions & Answers on πŸ‘‰ www.fullstack.cafe

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player