Possible Duplicate:
What is the reason behind “non-static method cannot be referenced from a static context”?
I am new to Java. I have following sets of code as below.
class Default
{
private short s;
private int i;
private long l;
private float f;
private double d;
private char c;
private String str;
private boolean b;
public static void main (String args[ ])
{
Default df = new Default();
System.out.println("\n Short = "+s);
System.out.println ("\n int i =" + i);
System.out.println ("\n long l =" + l );
System.out.println ("\n float f =" + f);
System.out.println ("\n double d =" + d);
System.out.println ("\n char c =" + c);
System.out.println ("\n String s =" + str);
System.out.println("\n boolean b =" + b);
}
}
This produces an error message as the subject of this question but following code works perfectly.
class Default
{
private short s;
private int i;
private long l;
private float f;
private double d;
private char c;
private String str;
private boolean b;
public static void main (String args[ ])
{
Default df = new Default();
System.out.println("\n Short = "+df.s);
System.out.println ("\n int i =" + df.i);
System.out.println ("\n long l =" + df.l );
System.out.println ("\n float f =" + df.f);
System.out.println ("\n double d =" + df.d);
System.out.println ("\n char c =" + df.c);
System.out.println ("\n String s =" + df.str);
System.out.println("\n boolean b =" + df.b);
}
}
This gives the desired result. What is the difference in these two set of code.
You have an instantiated object of
Defaultnameddfwhich is calling those variables. Since the variables you created are notstatic, they must be apart of some object that has been created.You use the keyword
staticif it is not used with an object. So you could just say:And then you can call
char canytime, which will benullbecause you haven’t given it a value yet.You use
staticwhen you will be using that variable or method without an object.