diff --git a/day08/src/com/inmind/static02/StaticDemo10.java b/day08/src/com/inmind/static02/StaticDemo10.java index 0592674..f0e26ca 100644 --- a/day08/src/com/inmind/static02/StaticDemo10.java +++ b/day08/src/com/inmind/static02/StaticDemo10.java @@ -6,9 +6,34 @@ static关键字的使用: 静态变量的使用方式: a.类名.静态变量名(推荐使用) b.对象名.静态变量名(不推荐使用) +2.使用static修饰成员方法的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都可以直接调用静态方法 + 区分 + a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用 + b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作 + 静态方法的使用方式: + a.类名.静态方法名(参数列表)(推荐使用) + b.对象名.静态方法名(参数列表)(不推荐使用) + +静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码, + 到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。 */ public class StaticDemo10 { + public static void main(String[] args) { + Student.showCount(); + //报道3个学生 + Student s1 = new Student("张三"); + Student s2 = new Student("李四"); + Student s3 = new Student("王五"); + //显示有多少个学生 + Student.showCount();//推荐写法 + //问张三你有多少个同学?? + s1.showCount();//不推荐!! + s2.showCount(); + s3.showCount(); + } + + public static void method01(String[] args) { //创建2个学生对象 Student s1 = new Student("张三"); Student s2 = new Student("李四"); @@ -20,6 +45,5 @@ public class StaticDemo10 { //问李四同学,你们在哪个教室上课??? s2.show(); - } } diff --git a/day08/src/com/inmind/static02/Student.java b/day08/src/com/inmind/static02/Student.java index fb1d26e..d07c5ee 100644 --- a/day08/src/com/inmind/static02/Student.java +++ b/day08/src/com/inmind/static02/Student.java @@ -5,15 +5,20 @@ public class Student { int age; int id; static String classRoom; //(静态变量)教室,但是教室只有一个,学生有n个,n个学生都使用同一个教室 - - public Student() { - } + static int studentCount;//该静态变量统计学生的数量 public Student(String name) { this.name = name; + //当唯一的构造方法调用时,就是创建了一个新的学生,总数就要加1 + studentCount++; } - public void show() { + public void show() {//成员方法(对象方法) System.out.println("姓名:"+name+"在"+classRoom+"教室上课"); } + + //展示有多少个学生 + public static void showCount(){//静态方法 + System.out.println("当前教室有"+studentCount+"个学生"); + } }