Seal a member
In this chapter you will learn:
Seal from overriding
We can stop overridding with seal
keyword.
class Shape{//from j a v a 2s . co m
public virtual int Area{
get{
return 0;
}
}
}
class Rectangle:Shape{
public int width;
public int height;
public sealed override int Area{
get{
return width * height;
}
}
}
Sealed methods
using System;// j av a 2 s . co m
public class BaseClass
{
public string lastName;
public string firstName;
public BaseClass(string lastName, string firstName)
{
this.lastName = lastName;
this.firstName = firstName;
}
public virtual void Accelerate()
{
Console.WriteLine("In BaseClass Accelerate() method");
Console.WriteLine(firstName + " accelerating");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(string lastName, string firstName) : base(lastName, firstName)
{
}
sealed public override void Accelerate()
{
Console.WriteLine("In DerivedClass Accelerate() method");
Console.WriteLine(firstName + " accelerating");
}
}
class MainClass
{
public static void Main()
{
DerivedClass myDerivedClass = new DerivedClass("A", "M");
Console.WriteLine("Calling myDerivedClass.Accelerate()");
myDerivedClass.Accelerate();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to use this keyword to reference current type
- How to use this keyword to avoid name hiding
- Invoke a constructor through this
Home » C# Tutorial » Class