Static关键字的那些事儿

定义

存储在静态区的变量或者方法

用途

咱先来看一个例子:
public class staticTest extends stasticTestDemo {
        int age;
        int height;
        String country;
        
}
......

public class stasticTestDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        staticTest p1=new staticTest();
        staticTest p2=new staticTest();
        
        p1.age=24;
        p1.height=165;
        
        p2.age=24;
        p2.height=172;
        
        p1.country="China";
        p2.country="China";
    }

}

我们可以从这个例子中看到,p1,p2中的country成员变量都是同一个值,如果说对于所有的stasticTest类的对象的country变量都是同样的,我们能不能用一种共享的变量来表示呢?
于是我们就可以使用static关键词,对该变量和方法设置成静态的,它们都会放到静态区中。也即是共享区,所有该类的对象都可以直接共用。
String country;----->static String country;
咱们再来看一个例子:


public class staticTest extends stasticTestDemo {
        int age;
        int height;
        static String country;
        
        public static void showAge()
        {
            System.out.println("Age:"+Age);
        }
        
}

结果报错,看一下

Cannot make a static reference to the non-static field age

这句话的大概意思就是age是非静态变量
也就是说,静态方法只能访问静态变量

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容