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

This commit is contained in:
xx
2026-09-22 15:09:31 +08:00
parent 4973afbd21
commit 17d3630c89
2 changed files with 48 additions and 2 deletions
+33
View File
@@ -0,0 +1,33 @@
package com.inmind.static02;
/*
static关键字的使用:
可以修饰成员变量和成员方法。
1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该变量的值
静态成员变量的使用方式:
a.类名.静态变量名(推荐使用)
b.对象名.静态变量名(不推荐使用)
2.使用static修饰成员方法的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都可以直接调用静态方法
区分
a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用
b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作
静态方法的使用方式:
a.类名.静态方法名(参数列表)(推荐使用)
b.对象名.静态方法名(参数列表)(不推荐使用)
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
*/
public class Demo09 {
public static void main(String[] args) {
//学生报名,计数,来了几位同学,统计
Student s1 = new Student("张三1", 18);
Student s2 = new Student("张三2", 18);
Student s3 = new Student("张三3", 18);
//校长问有多少同学了??
Student.showStudentCount();
s1.study();
}
}
+15 -2
View File
@@ -5,11 +5,24 @@ public class Student {
int age;
static String clazz;//班级
public Student() {
}
static int studentCount = 0;//学生总人数
public Student(String name, int age) {
this.name = name;
this.age = age;
//只要创建一个学生对象,那么学生人数就自动加1
studentCount++;
}
//静态方法,不再是一个成员方法了
public static void showStudentCount(){
System.out.println(studentCount);
}
//成员方法
public void study(){
}
}