From 2ef3d8ac9e5bc2c995edbc2f47b22a51a7fc0173 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Tue, 30 Dec 2025 15:37:55 +0800 Subject: [PATCH] =?UTF-8?q?day08--static=E5=85=B3=E9=94=AE=E5=AD=97?= =?UTF-8?q?=E7=9A=84=E5=BC=95=E5=85=A5=E5=92=8C=E4=BD=BF=E7=94=A8=E6=B3=A8?= =?UTF-8?q?=E6=84=8F=E4=BA=8B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day08/src/com/inmind/static02/Demo10.java | 36 ++++++++++++++++++++++ day08/src/com/inmind/static02/Student.java | 29 +++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 day08/src/com/inmind/static02/Demo10.java create mode 100644 day08/src/com/inmind/static02/Student.java diff --git a/day08/src/com/inmind/static02/Demo10.java b/day08/src/com/inmind/static02/Demo10.java new file mode 100644 index 0000000..d152b69 --- /dev/null +++ b/day08/src/com/inmind/static02/Demo10.java @@ -0,0 +1,36 @@ +package com.inmind.static02; +/* +static关键字的使用: +可以修饰成员变量和成员方法。 +1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该变量的值 +静态成员变量的使用方式: + a.类名.静态变量名(推荐使用) + b.对象名.静态变量名(不推荐使用) + +2.使用static修饰成员方法的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都可以直接调用静态方法 + 区分 + a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用 + b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作 + 静态方法的使用方式: + a.类名.静态方法名(参数列表)(推荐使用) + b.对象名.静态方法名(参数列表)(不推荐使用) + + 静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。 + */ +public class Demo10 { + public static void main(String[] args) { + //创建2个学生对象 + Student s1 = new Student(1, 21, "刘备"); + Student s2 = new Student(2, 22, "张飞"); +// System.out.println(s1.classRoom); +// System.out.println(Student.classRoom); +// s1.classRoom = "1903室"; + + Student.show(); + Student.classRoom = "1903室"; +// System.out.println(s2.classRoom);//"1903室" +// System.out.println(Student.classRoom);//"1903室" + Student.show(); + + } +} diff --git a/day08/src/com/inmind/static02/Student.java b/day08/src/com/inmind/static02/Student.java new file mode 100644 index 0000000..91b7687 --- /dev/null +++ b/day08/src/com/inmind/static02/Student.java @@ -0,0 +1,29 @@ +package com.inmind.static02; + +public class Student { + //属性(成员变量) + int id; + int age; + String name; + + //静态变量 + static String classRoom; + + + //构造方法(无参和有参) + + public Student() { + } + + public Student(int id, int age, String name) { + this.id = id; + this.age = age; + this.name = name; + } + + //(静态方法) + public static void show(){ + String showStr = "该同学在"+classRoom+"教室上课"; + System.out.println(showStr); + } +}