Difference between new and override keyword?

 Posted by Virendradugar on 9/1/2009 | Category: OOPS Interview questions | Views: 11535
Answer:

Let me explain this through code.

using System;

using System.Data;
using System.Text;
using System.Windows.Forms;

namespace BaseDerive
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

BaseClass b = new BaseClass();
b.func1();

DeriveClass d = new DeriveClass();
d.func1();

//Calls Base class function 1 as new keyword is used.
BaseClass bd = new DeriveClass();
bd.func1();

//Calls Derived class function 2 as override keyword is used.
BaseClass bd2 = new DeriveClass();
bd2.func2();

}
}

public class BaseClass
{
public virtual void func1()
{
MessageBox.Show("Base Class function 1.");
}

public virtual void func2()
{
MessageBox.Show("Base Class function 2.");
}

public void func3()
{
MessageBox.Show("Base Class function 3.");
}
}

public class DeriveClass : BaseClass
{
public new void func1()
{
MessageBox.Show("Derieve Class fuction 1 used new keyword");
}

public override void func2()
{
MessageBox.Show("Derieve Class fuction 2 used override keyword");
}

public void func3()
{
MessageBox.Show("Derieve Class fuction 3 used override keyword");
}

}
}



This is a window application so all the code for calling the function through objects is written in Form_Load event.
As seen in above code, I have declared 2 classes. One works as a Base class and second is a derieve class derived from base class.

Now the difference is

new: hides the base class function.
Override: overrides the base class function.


BaseClass objB = new DeriveClass();


If we create object like above notation and make a call to any function which exists in base class and derive class both, then it will always make a call to function of base class. If we have overidden the method in derive class then it wlll call the derive class function.

For example…

objB.func1(); //Calls the base class function. (In case of new keyword)

objB.func2(); //Calls the derive class function. (Override)
objB.func3(); //Calls the base class function.(Same prototype in both the class.)

Note:
// This will throw a compile time error. (Casting is required.)
DeriveClass objB = new BaseClass(); 


//This will throw run time error. (Unable to cast)
DeriveClass objB = (DeriveClass) new BaseClass(); 


Hope this helps!!!!!


Source: Prepared by me. | Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 1/15/2012 | Points: 10
Excellent information...cleared by doubts...

Thanks and Regards
Akiii

Login to post response

More Interview Questions by Virendradugar