Click to See Complete Forum and Search --> : Abstract, Virtual and Interface?


simmerheli
May 5th, 2006, 01:01 PM
Hi all:

I'm still not quite sure what the differences are between these things:

abstract:
virtual:
interface:

Anyone know the differences? :ehh:

Thanks

-Mike

jhammer
May 6th, 2006, 06:04 AM
virtual is used to enable derived classes to have thier own implementation of the method or property. By marking something as virtual, if someone calls the method of the object, the method that will be invoked belongs to the derived class.
Example:

public class Base
{
public virtual void Virt()
{
MessageBox.Show("Base.Virt");
}
public void NonVirt()
{
MessageBox.Show("Base.NonVirt");
}
}

public Derived:Base
{
public override void Virt()
{
MessageBox.Show("Derived.Virt");
}
public void NonVirt()
{
MessageBox.Show("Derived.NonVirt");
}
}

Main()
{
Base b = new Base();
Base d = new Derived();
Derived d1 = new Derived();
b.Virt(); //show: Base.Virt
b.NonVirt(); //show: Base.NonVirt
d.Virt(); //show: Derived.Virt
d.NonVirt(); //show: Base.NonVirt
d1.Virt(); //show: Derived.Virt
d1.NonVirt(); //show: Derived.NonVirt
}


An abstract method (or property) is a virtual member that is without implementation. That is - the derived classes will supply the implementation. You must mark the base class itself as abstract, and you cannot make instances of the abstract class. The abstract class can have non-absract methods (one abstract method is enough to mark the class as abstract). You must implement all the abstract methods in the derived class.

An interface is an abstract class, that has only abstract methods.