Object Oriented Programming

General C#

Interview Questions

What are the advantages of OOP?

In my opinion the major advantage of OOP is code reusability , maintainance and extensibility. Inheritance,Polymorphism and Encapsulation helps to achieve this. Lets see with a simple example.

Lets make a virtual zoo. We got a tiger and lion. We are going to add the animals to a list and have them make their sound one by one. I made an Animal class with Breath function and a property
animal name. Since all the animals breath, and all of them got a name we can reuse them by inhertiance. Then there is a virtual method(behavior) named MakeSound which will make the sound of the animal and demonstrate
a vital concept in OOP called polymorphism . The child classes can implement them with their own MakeNoise.

What will be the noise you hear( see on the output) on the first iteration of the foreach loop? Would it call the base class Animal.MakeNoise or Tiger.MakeNoise ( growl)? How does it work?

You will hear a growl. That is the beauty of polymorphism. Compiler knows that first animal object is type of Tiger and it delegates the call properly. This is a fundamental and very important concept in OOP.
As you can see, its so easy to add a new animal to your Zoo. Just derive it from the Animal class and implement the Animal's MakeNoise. Because breathing is already taken care of, you don't need to worry about that.

The whole trick is done by the "virtual" keyword( line 14 of the code ) and override keyword ( line 22 ).

So we demonstrated code reuse and polymorphism in this simple example. Happy OOPing!