static关键字

static关键字的作用:
1、使用static关键字修饰一个属性
声明为static的变量实质上就是全局变量
2、使用static关键修饰一个方法
通常,在一个类中定义一个方法为static,就是说,无需本类的对象即可调用此方法,类名.方法名  调用方法
3、使用static关键字修饰一个类(内部类)
/**
    static 关键字
    1、静态变量或方法不属于对象,但是依赖类
    2、静态变量是全局变量,生命周期从类被加载后一直到程序结束
    3、静态变量只存一份,在静态方法区中存储
    4、静态变量是本类所有对象共享一份
    5、建议不要使用对象名去调用静态数据,直接使用类名调用
    6、static修饰一个方法,那么该方法属于类,不属于对象,直接用:类名.方法名  调用
    7、静态方法不能访问非静态属性和方法,只能访问静态
*/

public class Test19 {

    public static void main(String[] args) {
        //Role role = new Role("刘备","蜀国");
        //Role role1 = new Role("云长","蜀国");
        //Role role2 = new Role("张飞","蜀国");
        Role role = new Role("刘备");
        Role role1 = new Role("云长");
        Role role2 = new Role("张飞");
        System.out.println(role.getInfo());
        System.out.println(role1.getInfo());
        System.out.println(role2.getInfo());
        
        System.out.println(role.country);
        System.out.println(role.country);
        System.out.println(role.country);
        role.country = "秦国"; //其中任意一个对象修改了静态变量值,其它对象调用都会更改
        System.out.println("--------------");
        System.out.println(role.country);
        System.out.println(role.country);
        System.out.println(role.country);
        
        System.out.println("--------------");
        System.out.println(Role.country);  //一般使用【类名.静态变量名】方式调用静态变量 

    }

}


class Role{
    private String name;
    static String country="蜀国"; //静态变量(全局变量)
    public Role(){
        
    }
    public Role(String name){  //当创建对象时传入的参数是一个,就会自动调用该只有一个参数的构造方法
        this.name=name;
    }
    public Role(String name,String country){
        this.name=name;
        this.country=country;
    }
    
    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }
    
    
    //静态方法不能访问非静态的数据
    public static void setCountry(String country){
        Role.country=country;
    }
    
    //静态变量就不用到getter and setter方法了
    /*
    public void setCountry(String country){
        this.country=country;
    }
    public String getCountry(){
        return country;
    }
    */
    
    public String getInfo(){
        return "name="+name+"country="+country;
    }
}
static关键字_第1张图片
微信截图_20181213203502.png

你可能感兴趣的:(static关键字)