在java中如果想在一个类中,调用另外一个类中的方法和变量,一般情况下是在这个类中,声明另外一个类的对象,然后引用对象名+方法或者属性。但是在类中 被static 修饰的属性,方法,除外。 当有static修饰的时候 调用类名+方法或者属性 因此在类库中有很多这样的方法,调用也比较方便。
class ClassB
int c=0;
public static void main(String[] args){
ClassA tt= new ClassA();
tt.ex();
c=tt.b;
System.out.println(c);
}
}
class ClassA{
int b=4;
public void ex(){
System.out.println("hahahha");
}
}
class ClassB{
int c=0;
public static void main(String[] args){
ClassA.ex();//类名加方法
System.out.println(ClassA.b);
}
}
class ClassA{
static int b=4;
public static void ex(){
System.out.println("hahahha");
}
}
static成员是不能被其所在class创建的实例访问的。
如果不加static修饰的成员是对象成员,也就是归每个对象所有的。
加static修饰的成员是类成员,就是可以由一个类直接调用,为所有对象共有的
在一个类中被static修饰的属性,计算机会在