楔子

  • 一旦用了static关键字,那么这样的内容就不再属于对象自己,而是属于类的,所以凡是本类的对象,都共享同一份
  • 静态先出现此时没有对象,对象的东西都没有办法用

正文

修饰成员变量

  • 只要有任意一个对象将其赋值那么所有的对象输出的都是一样的值
  • 可以做计数器使用

    • 添加private static 修饰

      1. public class Student {
      2. private int id;
      3. private String name;
      4. private int age;
      5. static int room;
      6. private static int counter;
      7. public int getId() {
      8. return id;
      9. }
      10. public void setId(int id) {
      11. this.id = id;
      12. }
      13. public Student() {
      14. this.id = ++counter;
      15. }
      16. public Student(String name, int age) {
      17. this.name = name;
      18. this.age = age;
      19. this.id = ++counter;
      20. }
      21. public String getName() {
      22. return name;
      23. }
      24. public void setName(String name) {
      25. this.name = name;
      26. }
      27. public int getAge() {
      28. return age;
      29. }
      30. public void setAge(int age) {
      31. this.age = age;
      32. }
      33. }

      修饰成员方法

  • 一旦使用static修饰成员方法,那么这就成为了静态方法,静态方法不属于对象,而是属于类的

  • 如果没有static关键字,那么必须创建对象,然后通过对象才可以使用
  • 对于静态方法来说,可以通过对象名进行调用,也可以直接通过类名称调用
  • 对于本类当中的静态方法可以省略类名称

无论是成员方法还是成员变量.如果有了static都推荐使用类名称进行调用
注意事项:

  • 静态只能访问静态,不能直接访问非静态(因为在内存当中是先有的静态后有的非静态),非静态则都可调用
    • 但是可以创建对象调用非静态,比如main函数
  • 静态方法中不能有this,因为this代表当前对象,谁调用的方法谁就是当前对象

静态代码块

  • 格式 ```java public class 类名称{

    static{

    1. 静态代码块内容

    }

} ```

  • 特点:当第一次用到本类时,静态代码块执行唯一的一次,静态内容总是优先于非静态,所以静态代码块比构造方法先执行
  • 典型用途:用来一次性的对静态成员变量进行赋值

内存中的位置

  • 静态成员位于方法区的静态区