How do you prevent another class from inheriting and/or prevent a class from overriding a member.
With C#, use the sealed keyword to prevent a class from being inherited from and to prevent a method from being overridden.
A method marked sealed must override an ancestor method. If you mark a class sealed, all members are implicitly not overridable so the sealed keyword on members is not legal.
public class Machine : System.Object{ public virtual void Speak(String pSentence) { MessageBox.Show(pSentence); }} public class Robot : Machine{ public sealed override void Speak(String pSentence) { MessageBox.Show(pSentence); }}
public sealed class Cyborg : Robot{ }
Make the constructor a private member of the class.
With Delphi, use the sealed keyword to prevent a class from being inherited from and use the final keyword to prevent a method from being overridden.
type
Robot = class sealed(TObject) public procedure Speak(pSentence: String); virtual; final; end;
Same keywords as Delphi (sealed uses slightly different syntax). With Prism, use the sealed keyword before the class keyword to prevent a class from being inherited from and use the final keyword to prevent a method from being overridden.
Robot = public sealed class(System.Object) public method Speak(pSentence: String); virtual; final; end;
In Java, there is the concept of a final class.
VB Classic supports a form of single level inheritance where you, in essence, create an abstract class and then implement it in one or more classes that inherit from the abstract class. However, you cannot have any further descendant classes so "prevent derivation" is implemented by design of this simple inheritance model.
With VB.Net, use the NotInheritable keyword to prevent a class from being inherited from and use the NotOverridable keyword to prevent a method from being overridden.
A method marked NotOverridable must override an ancestor method. If you mark a class NotInheritable, all members are implicitly not overridable so the NotOverridable keyword is not legal.
Public Class Machine
Public Overridable Sub Speak(ByRef pSentence As String) MessageBox.Show(pSentence) End SubEnd Class
Public Class Robot Inherits Machine
Public NotOverridable Overrides Sub Speak(ByRef pSentence As String) MessageBox.Show(pSentence) End SubEnd Class
Public NotInheritable Class Cyborg Inherits RobotEnd Class