Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A
dotnetinter

Can you explain a practical example of virtual and Override? ( C# OOP interview questions)

What we have?
Let’s say you have a class called Customer.
Customer class have following functions
Insert, Update and Delete.

What we will do with it?
Now let say there are some user interfaces called as EmployeeUI and ManagerUI which internally uses the Customer class and its functions.


What’s next?
Customer will demand a new UI from us called DirectorUI. Now this UI will also use Customer class and its functions.
But there is a problem. Update function is going to behave differently for this UI.

What we will do now?
We will go and some if conditions in Update function and make it working for all previous UIs as well as this new UI?

Is it the correct way?
Making changes in exiting customer class violates a Object oriented principle called OCP (Open closed principle) which says, “Software module should be closed for modification but open for extension”

Why it is required to follow such principle?
Customer class is already used in 2 UIs and successfully tested and proved.
Now making changes into it may lead to unexpected errors and complete re testing.

What is the correct solution?

Correct solution will be,

  • Make the existing Update function virtual.

  • Create a new class called CustomerForDirector which will inherit from Customer Class.

  • Override the virtual function in new class.

  • Now in DirectorUI just use this new Derived class instead of Customer class.

Also see the below c# OOP interview question video , what is the need of private constructor ?.



Also read http://questpond.blog.com/2013/09/09/can-you-talk-about-abstraction-and-encapsulation-in-detail-net-c-and-oop-interview-questions-with-answers/

http://dotnetinterviewquestion.wordpress.com/2013/09/09/can-you-explain-class-and-object-in-real-time-scenario-c-and-net-oop-interview-questions-with-answers/




Tags: abstraction and encapsulation interview , c# oop interview questions, classes and objects interview questions, csharp iterview questions, information technology questions, programmig iterview questios
Subscribe

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments