views:

211

answers:

5
+1  Q: 

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 static class and i is a static variable. How can I access this from a static main method. Is this way correct?

+2  A: 

Yes it's the correct way.

When a class is not static you need to instance it with new keyword. Like you did

Trial t1 = new Trial();

The static variable i shouldn't be static if you do not want to share its value between all Trial object. If you want to use this value (in "sharing mode") you can do it the way you did it. If you put this variable public you could simply do Trial.i = "your value"...

Daok
+2  A: 

Essentially, yes, but if you declare your accessors public static then you should be able to access them via the class name, ie, Trial.getI();

plinth
+1  A: 

You might wanna have the setter and getter as static, since they access a static variable. It might be very confusing to the user of the class if you can't see the source code, if you leave them as non static.

moose-in-the-jungle
A: 

Others have already mention that get and set methods should be static, since they are referring to a static variable.

Further, there is no such thing as static class in java. Also you aught to make that static variable private. So in that sense I am opposed to @Daok's suggestion of making it public.

As an example this works, but if you describe the actual use case it there may be some design errors that can be identified.

Hemal Pandya
A: 

Do you really want a static member variable? As mentioned above static variables are shared between all instances, thus t2.setI(x) means t1.getI() == x as well.

If you declare setters and getters static they can be accessed through the class rather than the instances. Trial.setI(x). Now it is clear to anyone that x is shared among all instances.

But i seems like what you really need is a non-static variable.

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

When running you main-method, the ouput will be 10 10 100

In contrast to using a static variable, which would print 10 100 100

frankern