From ed0dadb1a99291afa38e8ded3037c077b76505fc Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Tue, 20 Jan 2026 17:02:27 +0800 Subject: [PATCH] =?UTF-8?q?day08-=E9=9D=99=E6=80=81static=E5=85=B3?= =?UTF-8?q?=E9=94=AE=E5=AD=97=E4=BF=AE=E9=A5=B0=E6=88=90=E5=91=98=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day08/src/com/inmind/static02/Demo11.java | 34 ++++++++++++++++++++ day08/src/com/inmind/static02/Student.java | 37 +++++++++++++++++++++- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 day08/src/com/inmind/static02/Demo11.java diff --git a/day08/src/com/inmind/static02/Demo11.java b/day08/src/com/inmind/static02/Demo11.java new file mode 100644 index 0000000..712359e --- /dev/null +++ b/day08/src/com/inmind/static02/Demo11.java @@ -0,0 +1,34 @@ +package com.inmind.static02; +/* +静态变量的使用 +静态成员变量的使用方式: + a.类名.静态变量名(推荐使用) + b.对象名.静态变量名(不推荐使用) + +静态方法的使用 +使用static修饰成员方法的使用方式:只跟类有关,与对象无关了 + 区分 + a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用 + b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作 + 静态方法的使用方式: + a.类名.静态方法名(参数列表)(推荐使用) + b.对象名.静态方法名(参数列表)(不推荐使用) + + 静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。 + */ +public class Demo11 { + public static void main(String[] args) { + //给学生设置学号 + Student s1 = new Student(); + Student s2 = new Student(); + Student s3 = new Student(); + //询问3个同学的学号分别是什么 + System.out.println(s1.id); + System.out.println(s2.id); + System.out.println(s3.id); + //询问一个班级一共有多少个学生 + System.out.println(Student.studentCount); + System.out.println("---------------------------"); + Student.show(); + } +} diff --git a/day08/src/com/inmind/static02/Student.java b/day08/src/com/inmind/static02/Student.java index 8cec80d..8a46d0a 100644 --- a/day08/src/com/inmind/static02/Student.java +++ b/day08/src/com/inmind/static02/Student.java @@ -7,14 +7,49 @@ public class Student { int id; //静态变量(每个对象共享) static String clazz;//教室,这种变量,一个修改了,所有对象的内容都要改,就应该用static + //静态变量 + static int studentCount; + public Student(String name, int age, int id) { this.name = name; this.age = age; - this.id = id; + studentCount++; + this.id = studentCount; } public Student() { + //每次创建一个新的学生,都让共享的学生总数静态变量自增1 + studentCount++; + this.id = studentCount; + } + + + //静态方法 类方法 + + /* + 静态方法调用的注意事项: + 1.静态方法可以直接访问类变量(静态变量)和静态方法。 + 2.静态方法不能直接访问普通成员变量或成员方法。静态方法只能访问静态内容,反之,成员方法可以直接访问静态变量或静态方法。 + 3.静态方法中,不能使用this关键字。 + */ + public static void show(){ + System.out.println(studentCount); + System.out.println(clazz); + show1(); +// System.out.println(this);//静态方法中,不能使用this关键字。 +// System.out.println(name); 成员变量和成员方法在静态方法中都不能访问 +// show2(); + } + + public static void show1(){ + } + + public void show2(){//成员方法中可以访问静态内容 + System.out.println(studentCount); + System.out.println(clazz); + show1(); + System.out.println(this); } }