Книга: C# 2008 Programmer

Sealed Classes and Methods

Sealed Classes and Methods

So far you've seen the class definition for Shape, Rectangle, and Circle. Now let's define a class for the shape Square. As you know, a square is just a special version of rectangle; it just happens to have the same length and width. In this case, the Square class can simply inherit from the Rectangle class:

public class Square : Rectangle {}

You can instantiate the Square class as per normal and all the members available in the Rectangle would then be available to it:

Square s = new Square();
s.length = 5;
s.width = 5;
Console.WriteLine(s.Perimeter()); //---20--- 
Console.WriteLine(s.Area()); //---25--- 

To ensure that no other classes can derive from the Square class, you can seal it using the sealed keyword. A class prefixed with the sealed keyword prevents other classes inheriting from it. For example, if you seal the Square class, like this:

public sealed class Square : Rectangle {}

The following will result in an error:

//---Error: Square is sealed---
public class Rhombus : Square {}

A sealed class cannot contain virtual methods. In the following example, the Square class is sealed, so it cannot contain the virtual method called Diagonal():

public sealed class Square : Rectangle {
 //---Error: sealed class cannot contain virtual methods---
 public virtual Single Diagonal() {
  //---implementation here---
 }
}

This is logical because a sealed class does not provide an opportunity for a derived class to implement its virtual method. By the same argument, a sealed class also cannot contain abstract methods:

public sealed class Square : Rectangle {
 //---Error: sealed class cannot contain abstract method--- 
 public abstract Single Diagonal();
}

You can also seal methods so that other derived classes cannot override the implementation that you have provided in the current class. For example, recall that the Rectangle class provides the implementation for the abstract Area() method defined in the Shape class:

public class Rectangle : Shape {
 public override double Area() {
  return this.length * this.width;
 }
}

To prevent the derived classes of Rectangle (such as Square) from modifying the Area() implementation, prefix the method with the sealed keyword:

public class Rectangle : Shape {
 public override sealed double Area() {
  return this.length * this.width;
 }
}

Now if you try to override the Area() method in the Square class, you get an error:

public sealed class Square : Rectangle {
 //---Error: Area() is sealed in Rectangle class---
 public override double Area() {
  //---implementation here---
 }
}

Оглавление книги


Генерация: 0.031. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз