Saturday, March 1, 2014

Static : Class, Method, Constructor

Static Classes

A static class can be created using a keyword called "static" used at the class definition. A static class can contain only static members (static data members and static methods). You can‘t create an object for the static class.
Advantages:
  1. If you declare any non-static member, it generates a compile time error; so that it  is  guaranteed  that  the  class  contains  only  static  members;  no  chance  of declaring non-static member accidentally.
  2. When  you  try  to  create  an  instance  to  the  static  class,  it  again  generates  a compile time error, because the static members can be accessed directly with its class name.
 Syntax:
           static class classname
              {
                 //static data members
                 //static methods
              }


Download above code for Static Classes Demo : Download Links

Static Members

Types of Class Members:
  • Non-static Members:  This is the default type for all the members. If you are not using "static" keyword while the declaration of a field / property or a method, then it can be called as "Non-static member". The  main  feature  of  non-static  member  is  it  will  be  bounded  with  the  object only.
Non-static Fields / Properties:  The  memory  will  be  allocated,  when an object is created.
Non-static  Methods:  These  methods  can  implement  operations  on non-static fields and properties.
  • Static Members: If you are using "static" keyword while the declaration of a field / property or a method, then it can be called as "Static member". The main feature of non-static member is  -  it will not be bounded with the any object. It is individually accessible with the class name. In other words, the static members are accessible directly, without even creating one object also.
Static Fields / Properties:  The  memory  will  be  allocated  individually, without any relation with the object.
Static  Methods:  These  methods  can  implement  operations  on  static fields and properties only; and can‘t access the non-static members.

Download above code for Static Members :  Download Links

Static Constructors

The static constructor is used to initialize the ―static data members‖, whereas the normal constructor (non-static constructor) is used to initialize the non-static data members.
Syntax:
         static classname()
            {
               //some code
            }

Rules:
1.  Static constructors can‘t contain any access modifiers.
2.  Static constructors can‘t be defined with arguments.
3.  Static constructors can‘t access the non-static data members.

Download above code for Static Constructor :  Download Links

No comments:

Post a Comment

Flag Counter