Sealed Classes
Sealed class is the opposite of abstract class. When abstract class can not be instantiated as stand-alone class object, sealed class can only be instantiated as
stand-alone object. It can not be used as a base class.
Any attempt to use it as the base class of another class will produce a compile error. See following code sample:
Any attempt to use it as the base class of another class will produce a compile error. See following code sample:
public sealed class mySealedClass { public int myField; public void myMethod() { Console.WriteLine("This is my Sealed class"); } } public class inherritedClass : mySealedClass //compile error { .... }
Static Classes
A static class is a class where all the members are static. Static classes are used to group data and functions that are not affected by instance data.
A common use of a static class might be to create a math library containing sets of mathematical methods and values.
The important things to know about a static class are the following:
The important things to know about a static class are the following:
- The class itself must be marked
static
. - All the members of the class must be static.
- The class can have a static constructor, but it cannot have an instance constructor, since you cannot create an instance of the class.
- Static classes are implicitly sealed. That is, you cannot inherit from a static class.
static public class MyMath //static class, all members should be static { public static float PI = 3.14f; public static bool IsOdd(int x) { return x % 2 == 1; } public static int square(int x) { return x * x; } } class Program { static void Main( ) { int val = 3; Console.WriteLine(val + " is odd is " + MyMath.IsOdd(val)); Console.WriteLine("square(" + val + ") = " + MyMath.square(val)); } }
0 comments:
Post a Comment