2013-05-22 9 views
24

मेरा असाइनमेंट एक आवृत्ति चर, एक स्ट्रिंग के साथ एक प्रोग्राम बनाना है, जिसे उपयोगकर्ता द्वारा इनपुट किया जाना चाहिए। लेकिन मुझे यह भी नहीं पता कि एक आवृत्ति चर क्या है। एक आवृत्ति चर क्या है? मैं एक कैसे बना सकता हूं? यह क्या करता है?जावा- एक आवृत्ति चर क्या है?

+2

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html – Maroun

उत्तर

52

उदाहरण चर चर एक क्लास के भीतर घोषित किया जाता है दिखाता है, लेकिन एक विधि के बाहर: कुछ की तरह:

class IronMan{ 

    /** These are all instance variables **/ 
    public String realName; 
    public String[] superPowers; 
    public int age; 

    /** Getters/setters here **/ 
} 

अब इस IronMan इन चरों का उपयोग करने के लिए कक्षा को अन्य कक्षा में तत्काल स्थापित किया जा सकता है, जैसे:

class Avengers{ 
     public static void main(String[] a){ 
       IronMan ironman = new IronMan(); 
       ironman.realName = "Tony Stark"; 
       // or 
       ironman.setAge(30); 
     } 

} 

इस प्रकार हम इंस्टेंस चर का उपयोग करते हैं। जावा मूल बातें here पर अधिक मजेदार सामान।

19

एक आवृत्ति चर एक चर है जो एक वर्ग के उदाहरण का सदस्य है (यानी new के साथ बनाए गए किसी चीज़ से जुड़ा हुआ है), जबकि कक्षा चर वर्ग के सदस्य हैं।

कक्षा के प्रत्येक उदाहरण में एक आवृत्ति चर की अपनी प्रति होगी, जबकि वर्ग के साथ जुड़े प्रत्येक स्थैतिक (या कक्षा) चर के केवल 1 में से एक है।

difference-between-a-class-variable-and-an-instance-variable

यह परीक्षण वर्ग अंतर

public class Test { 

    public static String classVariable="I am associated with the class"; 
    public String instanceVariable="I am associated with the instance"; 

    public void setText(String string){ 
     this.instanceVariable=string; 
    } 

    public static void setClassText(String string){ 
     classVariable=string; 
    } 

    public static void main(String[] args) { 
     Test test1=new Test(); 
     Test test2=new Test(); 

     //change test1's instance variable 
     test1.setText("Changed"); 
     System.out.println(test1.instanceVariable); //prints "Changed" 
     //test2 is unaffected 
     System.out.println(test2.instanceVariable);//prints "I am associated with the instance" 

     //change class variable (associated with the class itself) 
     Test.setClassText("Changed class text"); 
     System.out.println(Test.classVariable);//prints "Changed class text" 

     //can access static fields through an instance, but there still is only 1 
     //(not best practice to access static variables through instance) 
     System.out.println(test1.classVariable);//prints "Changed class text" 
     System.out.println(test2.classVariable);//prints "Changed class text" 
    } 
} 
+0

सही। आप किसी ऑब्जेक्ट में 'फ़ील्ड' के रूप में एक आवृत्ति चर के बारे में भी सोच सकते हैं। एक प्रासंगिक अवधारणा encapsulation है (देखें: 'निजी' पहुंच संशोधक, गेटर्स और सेटर्स ...) – vikingsteve

+0

दरअसल, मैंने अधिकांश चीजों को आसान पहुंच के लिए सार्वजनिक घोषित कर दिया है, यह आमतौर पर एक बुरा विचार है –

संबंधित मुद्दे