Java – static concepts

javastatic

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?

Best Solution

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"...