static关键字

一、作用:是一个修饰符,用于修饰成员(成员变量,成员方法)
1、被static 修饰后的成员变量只有一份
2、当成员被static修饰之后,多了一种访问方式,除了可以被对象调用之外还可以被类名直接调用(类名.静态成员)


二、static的特点:
1、随着类的加载而被加载
2、优先于对象的存在
3、被所有的对象所共享的
4、可以直接被类名做调用

三、存放位置:
1、静态成员属性(类变量)随着类的加载而存在于data内存区。
2、普通成员属性随着对象的建立而存在于堆内存。

四、生命周期:
1、静态成员(类变量)生命周期最长,随着类的消失而消失
2、非静态成员(实例变量)生命周期比静态成员短,随着对象的消失而消失

五、方法的注意事项:
1、静态的方法只能访问静态的成员
2、非静态的方法即能访问静态的成员(成员属性,成员方法)也能访问非静态的成员
3、今天方法中是不可以定义 this、super关键字,因为静态优先于对象存在,所以静态方法不可以出现this

 
代码:
 
class demo1
{
    public static void main(String[] args)
    {
        Student stu = new Student("小米","中国");
        stu.study();
        Student stu1 = new Student("小明","中国11");

         System.out.println(stu.country);
         System.out.println(stu1.country);
    }
}



class Student{

    String name;
    static String country;

public Student(String name,String country){
    
           this.name = name;
           this.country = country;
    }

//public Student(){}

    public void study(){
    
      System.out.println(country+"的"+name+"在学习");
    }

原文地址:https://www.cnblogs.com/yuguangblog/p/6068540.html