day08--static内存执行图解&注意事项分析
This commit is contained in:
@@ -16,6 +16,17 @@ static关键字的使用:
|
|||||||
b.对象名.静态方法名(参数列表)(不推荐使用)
|
b.对象名.静态方法名(参数列表)(不推荐使用)
|
||||||
|
|
||||||
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
|
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
静态方法调用的注意事项:
|
||||||
|
1.静态方法可以直接访问类变量(静态变量)和静态方法。
|
||||||
|
2.静态方法不能直接访问普通成员变量或成员方法。静态方法只能访问静态内容,反之,成员方法可以直接访问静态变量或静态方法。(先人(刘邦)不知道(张三)后人,后人(张三)是知道先人(刘邦)的)
|
||||||
|
3.静态方法中,不能使用this关键字。
|
||||||
|
|
||||||
|
static 修饰的内容:
|
||||||
|
是随着类的加载而加载的,且只加载一次。(只跟类有关)
|
||||||
|
存储于一块固定的内存区域(静态区),所以,可以直接被类名调用。
|
||||||
|
它优先于对象存在,所以,可以被所有对象共享。
|
||||||
*/
|
*/
|
||||||
public class Demo10 {
|
public class Demo10 {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@@ -26,11 +37,11 @@ public class Demo10 {
|
|||||||
// System.out.println(Student.classRoom);
|
// System.out.println(Student.classRoom);
|
||||||
// s1.classRoom = "1903室";
|
// s1.classRoom = "1903室";
|
||||||
|
|
||||||
Student.show();
|
Student.showRoom();
|
||||||
Student.classRoom = "1903室";
|
Student.classRoom = "1903室";
|
||||||
// System.out.println(s2.classRoom);//"1903室"
|
// System.out.println(s2.classRoom);//"1903室"
|
||||||
// System.out.println(Student.classRoom);//"1903室"
|
// System.out.println(Student.classRoom);//"1903室"
|
||||||
Student.show();
|
Student.showRoom();
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,25 +5,26 @@ public class Student {
|
|||||||
int id;
|
int id;
|
||||||
int age;
|
int age;
|
||||||
String name;
|
String name;
|
||||||
|
|
||||||
//静态变量
|
//静态变量
|
||||||
static String classRoom;
|
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() {
|
||||||
}
|
}
|
||||||
|
|
||||||
public Student(int id, int age, String name) {
|
public Student(int id, int age, String name) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.age = age;
|
this.age = age;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
//(静态方法)
|
|
||||||
public static void show(){
|
|
||||||
String showStr = "该同学在"+classRoom+"教室上课";
|
|
||||||
System.out.println(showStr);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user