可能重複:
What is the reason behind 「non-static method cannot be referenced from a static context」?的Java:非靜態變量這不能從靜態上下文中引用
我是新來的Java。我有以下幾組代碼,如下所示。
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);
}
}
這產生了一個錯誤消息作爲這個問題的主題,但下面的代碼完美的作品。
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);
}
}
這給出了期望的結果。這兩組代碼有什麼區別。
aroth的回覆非常有助於可視化差異。謝謝。 – user1837224