JScript .NET, Part III: Classes and Namespaces: Specifying Member Visibility - Doc JavaScript | WebReference

JScript .NET, Part III: Classes and Namespaces: Specifying Member Visibility - Doc JavaScript


JScript .NET, Part III: Classes and Namespaces

Specifying Member Visibility

You have probably noticed the static modifier in some of the examples we showed in this and previous columns about JScript .NET. The static modifier labels a class member as belonging to the class itself and not to any one of the instances that are created from the class. You can access a static member only when referencing the class rather than referencing its instances. The static modifier can be applied to properties and methods of the class. It cannot be applied to member classes, interfaces, and members of interfaces. You may not combine the static modifier with any of abstract, final, hide, or override. Do not confuse the static modifier with the static statement which is used to label a block of code that initializes static variables.

The following code demonstrates the use of the static modifier:

class Demo {
   var NonstaticVar : int;
   // A non-static field belonging to a class instance.
   static var StaticVar : int;
   // A static field belonging to the class.
}
// Initialize StaticVar. An instance of Demo is not needed.
Demo.StaticVar = 42;
// Create an instance of Demo class.
var MyDemo : Demo = new Demo;
MyDemo.NonstaticVar = 5;
// The static field is not directly
// accessible from the class instance.
print(MyDemo.NonstaticVar);
print(Demo.StaticVar);

The output of this program is:

5
42

The public modifier makes a member of a class visible to any code that has access to the class. All classes and interfaces are public by default. You cannot combine the public modifier with any of the following three modifiers: private, protected, and internal. You put this modifier in front of the var token.

The private modifier makes a member of a class or interface visible within that class or interface only. Any member of a class or interface, including nested members, can be marked with private. You may not combine the private modifier with any of these three: public, internal, and protected.

The protected modifier makes a member of a class or interface visible within that class or interface and within all derived classes of the current class. Any member of a class or interface, including nested members, can be marked with protected. You cannot tag members of classes in the global scope with protected. You may not combine the protected modifier with any of these three: private, internal, and public.


Next: A Final Word


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: May 6, 2002
Revised: May 6, 2002

URL: http://www.webreference.com/js/column109/6.html