day08-静态static关键字修饰成员方法

This commit is contained in:
2026-05-16 15:41:47 +08:00
parent b36603b570
commit 2ccb704e31
2 changed files with 49 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
package com.inmind.static02;
/*
static关键字的使用
2.使用static修饰成员方法的使用方式只跟类有关与对象无关了并且该类的每个对象都可以直接调用静态方法
区分
a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用
b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作
静态方法的使用方式:
a.类名.静态方法名(参数列表)(推荐使用)
b.对象名.静态方法名(参数列表)(不推荐使用)
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
*/
public class Demo09 {
public static void main(String[] args) {
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 19);
Student.clazz = "1903室";
//调用静态方法
Student.show();
s1.show();
s2.show();
}
}

View File

@@ -16,4 +16,27 @@ public class Student {
this.name = name;
this.age = age;
}
//静态方法,只跟类有关
public static void show(){
System.out.println("学生的教室为:"+clazz);
}
//成员方法(对象方法),只跟对象有关
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}