关于包的问题

来源:百度知道 编辑:UC知道 时间:2024/05/15 10:21:17
以下是我建的个包:
package adder;

public class add {
public int x,y;
public int add1(int x, int y){
return x+y;
}
}
测试程序:
import adder.*;
public class test {
static int a=3;
static int b=5;
public static void main(String[] args){
add d=new add();
int c=d.add1(a, b);
System.out.println(c);
}
}
在测试程序里面 定义a和b的时候为什么要在前面加static???

因为 a,b 在main方法中别调用。main是静态方法
java语法规定在静态方法中直接调用成员变量必须也是静态。
这是因为 类静态的方法和变量是在类加载时就被创建出来,早于类的成员方法和变量(他们只有你在new他的时候才在内存中分配空间创建出来)。

所以如果你不想用static 修饰a,b。而想在想main这样的静态方法中调用的话。
应该方法中这样。 test t = new test(); add d = new add(); int c= d.add(t.a,t.b); System.out.println(c);

另外按照约定俗成的习惯类名应该大写

因为你想直接在main中用a,b main是静态的方法,所以你要加上static

因为主方法是静态的,要调用该内里面的成员变量,只能调用静态成员变量,所以必须在变量前 加static

静态方法里只能使用静态变量