Static Members क्या हैं
Static members एक object के बजाय पूरी class से belong करते हैं, जैसे school की घंटी जो सबके लिए बजती है। आप उन्हें बिना कोई object बनाए class name के ज़रिए उपयोग करते हैं।
In this page:
Syntax
class ClassName
{
public static type Field;
public static ReturnType MethodName() { }
}
ClassName.Field;
ClassName.MethodName(); // no object needed
Static Members
static fields और methods खुद class से belong करते हैं, किसी individual object से नहीं, और हर instance में share होते हैं। आप उन्हें किसी object reference के बजाय class name के ज़रिए call करते हैं।
Static members counters, utility methods, और shared configuration के लिए उपयोगी हैं।
Note:
यह गिनने का एक अच्छा तरीका है कि किसी class के कितने instances बन चुके हैं, एक static field का उपयोग करके।
उदाहरण: Static Members
using System;
class Counter
{
public static int InstanceCount = 0;
public Counter()
{
InstanceCount++;
}
public static int Double(int n) => n * 2;
}
class Program
{
static void Main(string[] args)
{
new Counter();
new Counter();
new Counter();
Console.WriteLine(Counter.InstanceCount);
Console.WriteLine(Counter.Double(21));
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- बिना किसी object के किसी static method से एक instance member access करने की कोशिश करना।
- यह उम्मीद करना कि हर object की किसी static field की अपनी copy होगी, जबकि यह सबके बीच share होती है।
- हर जगह static उपयोग करना, जो code को test करना मुश्किल बनाता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: