• Java static关键字


    概念

    使用static关键字修饰成员变量表示静态的含义,此时成员变量由对象层级提升为类层级,也就是整个类只有一份并被所有对象共享,该成员变量随着类的加载准备就绪,与是否创建对象无关。

     static关键字修饰的成员可以使用引用.的方式访问,但推荐类名.的方式。如:Person.id

    使用方式 

    • 在非静态成员方法中既能访问非静态的成员又能访问静态的成员。 (成员:成员变量 + 成员方法, 静态成员被所有对象共享)

    例子如下:

    public class People {

      String name;

      static String country;
      public void show() {
    System.out.println("我是" + name + ",今年" +age + "岁了,来自" + getCountry());
    }


    }
    public class PeopleTest {

    public static void main(String[] args) {
           People  p1 = new People();
    p1.show(); //show方法为非静态方法,可以访问静态、非静态方法

    }
    }

    • 在静态成员方法中只能访问静态成员不能访问非静态成员。 (成员:成员变量 + 成员方法, 因为此时可能还没有创建对象)

    静态成员方法访问非静态(即不包含static的变量)会报错,例子如下:

    public class People {

      private String country; // 隶属于对象层级,也就是每个对象都拥有独立的一份
    public static String getCountry() {
    return country;
    }
    }
    public class PeopleTest {

    public static void main(String[] args) {
       System.out.println("获取到的国籍信息是:" + People.getCountry()); // 报错:java: 无法从静态上下文中引用非静态 变量 country,若想成功访问,需在变量前加static,如:private String static id
    }
    }

    • 在以后的开发中只有隶属于类层级并被所有对象共享的内容才可以使用 static关键字修饰。(不能滥用static关键字)


  • 相关阅读:
    VMware安装Centos7超详细过程
    LVS+Keepalived小试牛刀
    Spring入门之AOP篇
    Spring学习笔记及资源
    Spring入门第一例
    Mybatis学习手记(二)
    Mybatis学习手记(一)
    java web 开发入门实例
    关于JAVA编译时找不到自定义包的问题
    Java 学习笔记及资源
  • 原文地址:https://www.cnblogs.com/goldenwangyi/p/15031594.html
Copyright © 2020-2023  润新知