C# Override methods
In this chapter you will learn:
Virtual and override member function
class Class1/*from w w w . j av a 2 s.c o m*/
{
public virtual void Hello()
{
System.Console.Write( "Hello from Class1" );
}
}
class Class2 : Class1
{
public override void Hello()
{
base.Hello();
System.Console.Write( " and hello from Class2 too" );
}
public static void Main( string[] args )
{
Class2 c2 = new Class2();
c2.Hello();
}
}
The code above generates the following result.
new method not override
using System;//from www .jav a 2 s . co m
class BaseClass
{
virtual public void Print()
{ Console.WriteLine("This is the base class."); }
}
class DerivedClass : BaseClass
{
override public void Print()
{ Console.WriteLine("This is the derived class."); }
}
class SecondDerived : DerivedClass
{
new public void Print()
{
Console.WriteLine("This is the second derived class.");
}
}
class MainClass
{
static void Main()
{
SecondDerived derived = new SecondDerived();
BaseClass mybc = (BaseClass)derived;
derived.Print();
mybc.Print();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: