day08-静态static关键字修饰成员方法
This commit is contained in:
34
day08/src/com/inmind/static02/Demo11.java
Normal file
34
day08/src/com/inmind/static02/Demo11.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.inmind.static02;
|
||||
/*
|
||||
静态变量的使用
|
||||
静态成员变量的使用方式:
|
||||
a.类名.静态变量名(推荐使用)
|
||||
b.对象名.静态变量名(不推荐使用)
|
||||
|
||||
静态方法的使用
|
||||
使用static修饰成员方法的使用方式:只跟类有关,与对象无关了
|
||||
区分
|
||||
a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用
|
||||
b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作
|
||||
静态方法的使用方式:
|
||||
a.类名.静态方法名(参数列表)(推荐使用)
|
||||
b.对象名.静态方法名(参数列表)(不推荐使用)
|
||||
|
||||
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
|
||||
*/
|
||||
public class Demo11 {
|
||||
public static void main(String[] args) {
|
||||
//给学生设置学号
|
||||
Student s1 = new Student();
|
||||
Student s2 = new Student();
|
||||
Student s3 = new Student();
|
||||
//询问3个同学的学号分别是什么
|
||||
System.out.println(s1.id);
|
||||
System.out.println(s2.id);
|
||||
System.out.println(s3.id);
|
||||
//询问一个班级一共有多少个学生
|
||||
System.out.println(Student.studentCount);
|
||||
System.out.println("---------------------------");
|
||||
Student.show();
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,49 @@ public class Student {
|
||||
int id;
|
||||
//静态变量(每个对象共享)
|
||||
static String clazz;//教室,这种变量,一个修改了,所有对象的内容都要改,就应该用static
|
||||
//静态变量
|
||||
static int studentCount;
|
||||
|
||||
|
||||
public Student(String name, int age, int id) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.id = id;
|
||||
studentCount++;
|
||||
this.id = studentCount;
|
||||
}
|
||||
|
||||
public Student() {
|
||||
//每次创建一个新的学生,都让共享的学生总数静态变量自增1
|
||||
studentCount++;
|
||||
this.id = studentCount;
|
||||
}
|
||||
|
||||
|
||||
//静态方法 类方法
|
||||
|
||||
/*
|
||||
静态方法调用的注意事项:
|
||||
1.静态方法可以直接访问类变量(静态变量)和静态方法。
|
||||
2.静态方法不能直接访问普通成员变量或成员方法。静态方法只能访问静态内容,反之,成员方法可以直接访问静态变量或静态方法。
|
||||
3.静态方法中,不能使用this关键字。
|
||||
*/
|
||||
public static void show(){
|
||||
System.out.println(studentCount);
|
||||
System.out.println(clazz);
|
||||
show1();
|
||||
// System.out.println(this);//静态方法中,不能使用this关键字。
|
||||
// System.out.println(name); 成员变量和成员方法在静态方法中都不能访问
|
||||
// show2();
|
||||
}
|
||||
|
||||
public static void show1(){
|
||||
}
|
||||
|
||||
public void show2(){//成员方法中可以访问静态内容
|
||||
System.out.println(studentCount);
|
||||
System.out.println(clazz);
|
||||
show1();
|
||||
System.out.println(this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user