From 4073285850937fb6655ee5072adbd3bdcc9c3e9d Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Tue, 30 Dec 2025 16:14:35 +0800 Subject: [PATCH] =?UTF-8?q?day08--static=E5=86=85=E5=AD=98=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E5=9B=BE=E8=A7=A3&=E6=B3=A8=E6=84=8F=E4=BA=8B?= =?UTF-8?q?=E9=A1=B9=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day08/src/com/inmind/static02/Demo10.java | 15 +++++++++++++-- day08/src/com/inmind/static02/Student.java | 21 +++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/day08/src/com/inmind/static02/Demo10.java b/day08/src/com/inmind/static02/Demo10.java index d152b69..c6088a7 100644 --- a/day08/src/com/inmind/static02/Demo10.java +++ b/day08/src/com/inmind/static02/Demo10.java @@ -16,6 +16,17 @@ static关键字的使用: b.对象名.静态方法名(参数列表)(不推荐使用) 静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。 + --------------------------------------------------- + +静态方法调用的注意事项: +1.静态方法可以直接访问类变量(静态变量)和静态方法。 +2.静态方法不能直接访问普通成员变量或成员方法。静态方法只能访问静态内容,反之,成员方法可以直接访问静态变量或静态方法。(先人(刘邦)不知道(张三)后人,后人(张三)是知道先人(刘邦)的) +3.静态方法中,不能使用this关键字。 + +static 修饰的内容: +是随着类的加载而加载的,且只加载一次。(只跟类有关) +存储于一块固定的内存区域(静态区),所以,可以直接被类名调用。 +它优先于对象存在,所以,可以被所有对象共享。 */ public class Demo10 { public static void main(String[] args) { @@ -26,11 +37,11 @@ public class Demo10 { // System.out.println(Student.classRoom); // s1.classRoom = "1903室"; - Student.show(); + Student.showRoom(); Student.classRoom = "1903室"; // System.out.println(s2.classRoom);//"1903室" // System.out.println(Student.classRoom);//"1903室" - Student.show(); + Student.showRoom(); } } diff --git a/day08/src/com/inmind/static02/Student.java b/day08/src/com/inmind/static02/Student.java index 91b7687..e3be4a7 100644 --- a/day08/src/com/inmind/static02/Student.java +++ b/day08/src/com/inmind/static02/Student.java @@ -5,25 +5,26 @@ public class Student { int id; int age; String name; - //静态变量 static String classRoom; + //行为(成员方法) + public void show(){ + String showStr = "学号为"+this.id+",年龄为"+age+",姓名为"+this.name+"在"+classRoom+"教室上课"; + System.out.println(showStr); + showRoom(); + } + //静态方法 + public static void showRoom(){ + String showStr = "该同学在"+classRoom+"教室上课"; + System.out.println(showStr); + } - //构造方法(无参和有参) - 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); - } }