Java – 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(); 
        Trial t2 = new Trial(); 

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