一个类中的类成员方法(有static关键字修饰)能否访问该类中的实例成员变量(没
来源:百度知道 编辑:UC知道 时间:2024/05/12 06:00:36
静态方法就是不需要实例化就可以访问的方法.而成员方法就需要实例化之后才能访问.
我们编程要有一个内存模型的概念.静态的方法是类的方法,它随类的加载而产生,实例方法需要实例化一个对象之后,它会在内存分配一个地址,然后你才能操作它.
例如:
class Example {
public static void display() {
System.out.println("类的方法");
}
public void displayOne() {
System.out.println("对象的方法");
}
public static void main(String[] args) {
Example.display();
Example e=new Example();
e.displayOne();
e.display();
}
}
第一个不可以,第二个可以。
静态方法只可以访问静态变量。
下面是个简单的例子。
public class Answer {
static int a = 0;
int b = 0;
public static void main(String[] args){
Print c = new Print();
c.callStatic(a);
System.out.println(b);//Cannot make a static reference to the non-static field b
}
}
public class Print {
public void callStatic(int value){
System.out.println(value);
}
}
这里main就是个静态方法,而pr