Sealed class
A sealed class cannot be inherited from. It is recommended for classes that won't be derived from, or only contain static methods / properties. Typically only used if writing a library.Abstract class
An abstract class is used to represent something (an abstraction) that should never be instantiated. You must derive from an abstract class. All abstract classes must be overridden. An abstract class establishes a "contract" for all derived classes.public abstract class Control
{
protected int top;
protected int left;
public Control(int top, int left)
{
this.top = top;
this.left = left;
}
public class Button : Control
{
public string Contents;
public class Button(int top, int left, string contents)
: base(top, left)
{
Contents = contents;
}
}
In your program you cannot do this
Control c = new Control();
because you cannot create an instance of a control as it is declared abstract.
However you can create an instance of a derived class - i.e. create the concrete class - and assign that to a variable of type Control.
Control button = new Button(2, 3, "New Button");
The benefit of this is that you can create a collection of Control objects and iterate over them because all variables are of the same type, control. You can execute the abstract method in the base class, and each concrete class will execute that correctly because they override the abstract base method in their own way. Polymorphism is at work again.
No comments:
Post a Comment