Java Static Members In Hindi

📔 : Java 🔗

पिछले Topic में आपने समझा कि Class / Object क्या होते हैं और इन्हे कैसे define करते हैं। जैसा कि आपने पहले भी पढ़ा है कि किसी भी Class में दो तरह के members (Variables / Methods ) हो सकते हैं , Static & Non Static . इस Topic में आप पढ़ेंगे कि Class में Static Members क्या होता है , कैसे इन्हे define करते हैं और किस - किस तरह से इन्हे Access कर सकते हैं।

Java Defining Static Members

Java में Static Variables / Methods को define करने के लिए simply predefined keyword static का use किया जाता है। किसी भी Variable / Method से पहले static लिख देने से वह Property As a static define हो जाती है।
For Example :

// define static variable.
static int age;

//define static method.
static void print_age(){
  // code of block.
}

Java Accessing Static Members

C++ में Static Property / Methods Access करने के लिए हमें उस class का Object नहीं बनाना पड़ता है , simply ClassName और dot operator (.) का use करके हम directly Class की Static variable / Methods Access कर सकते हैं।

Java Static Member Example

File : StaticMember.java

CopyFullscreenClose FullscreenRun
public class StaticMember {
  // define static method.
  static void my_method() {
     System.out.println("Test Method..");
  }
  
  // define static variable.
  static String message = "Hello";
 
  public static void main(String[] args) {
    // now access them with class name.
    StaticMember.my_method();
    System.out.println(StaticMember.message);
  }
}
Output
javac StaticMember.java
java StaticMember
Test Method..
Hello

Class name is optional

static members को हम बिना Class name से तो access कर ही सकते हैं , हालाँकि आप class के अंदर इन्हे directly (without class name) भी call कर सकते हैं।

File : StaticMember.java

CopyFullscreenClose FullscreenRun
public class StaticMember {
  static void my_method() {
     System.out.println("Test Method..");
  }
 
  static String message = "Hello";
 
  public static void main(String[] args) {
    // now access them without class name.
    my_method();
    System.out.println(message);
  }
}
Output
javac StaticMember.java
java StaticMember
Test Method..
Hello

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers