Static concepts

class Trial 
{   static int i; 
    int getI() 
    {       return i;} 
    void setI(int value) 
    {       i = value;} 
} 
public class ttest 
{  public static void main(String args[]) 
   {    Trial t1 = new Trial(); 
        t1.setI(10); 
        System.out.println(t1.getI()); 
        Trial t2 = new Trial(); 
        t2.setI(100); 
        System.out.println(t1.getI()); 
        System.out.println(t2.getI()); 
   } 
}

      

Here trial is a non-stationary class and i am a static variable. How can I access this from a static main method. Is it correct?

+1


source to share


5 answers


Yes, that's the right way.

When the class is not static, you need to specify it with a new keyword. How did you do



Trial t1 = new Trial(); 

      

Static variable i shouldn't be static unless you want to share its value between all probe objects. If you want to use this value (in shared mode), you can do it the way you did it. If you put this variable public, you can just do Trial.i = "your value" ...

+3


source


Essentially yes, but if you declare your public access statistics, you must be able to access them through the class name, that is, Trial.getI ();



+2


source


Perhaps you want the setter and getter to become static as they access a static variable. It can be very confusing for the user of this class if you can't see the source code if left as non-static.

+1


source


Others have already mentioned that get and set methods must be static because they refer to a static variable.

Also, there is no such thing as a static class in java . You must also make this static variable private. So in that sense, I am opposed to @Daok's suggestion to post it.

This works as an example, but if you are describing an actual use case, there might be some design errors that can be identified.

0


source


Do you really need a static member variable? As mentioned above, static variables are shared across all instances, so t2.setI (x) means t1.getI () == x.

If you declare setters and getters static, they can be accessed through the class, not instances. Trial.setI (x). It is now clear to everyone that x is common to all instances.

But it seems to me that you really need a non-static variable.

class Trial {   
    private int i; 
    int getI() { return i;} 
    void setI(int value) {i = value;} 
} 

      

When running your main method, the output will be 10 10 100

As opposed to using a static variable which will print 10 100 100

0


source







All Articles