day08--static关键字的引入和使用注意事项
This commit is contained in:
36
day08/src/com/inmind/static02/Demo10.java
Normal file
36
day08/src/com/inmind/static02/Demo10.java
Normal file
@@ -0,0 +1,36 @@
|
||||
package com.inmind.static02;
|
||||
/*
|
||||
static关键字的使用:
|
||||
可以修饰成员变量和成员方法。
|
||||
1.使用static修饰成员变量的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都共享了该变量的值
|
||||
静态成员变量的使用方式:
|
||||
a.类名.静态变量名(推荐使用)
|
||||
b.对象名.静态变量名(不推荐使用)
|
||||
|
||||
2.使用static修饰成员方法的使用方式:只跟类有关,与对象无关了,并且该类的每个对象都可以直接调用静态方法
|
||||
区分
|
||||
a.自定义成员方法:(对象方法),它的定义是给每个对象来调用,必须通过创建对象来调用
|
||||
b 静态方法:(类方法),它的定义是给对应的类直接调用,跟每个对象无关的操作
|
||||
静态方法的使用方式:
|
||||
a.类名.静态方法名(参数列表)(推荐使用)
|
||||
b.对象名.静态方法名(参数列表)(不推荐使用)
|
||||
|
||||
静态方法的作用:静态方法调用的比较方便,不需要创建对象,常用于对应的工具类的抽取,在一个项目中有可能有特定的功能代码,到处都要用,抽取成静态方法,直接通过类名.静态方法名,直接调用功能即可。
|
||||
*/
|
||||
public class Demo10 {
|
||||
public static void main(String[] args) {
|
||||
//创建2个学生对象
|
||||
Student s1 = new Student(1, 21, "刘备");
|
||||
Student s2 = new Student(2, 22, "张飞");
|
||||
// System.out.println(s1.classRoom);
|
||||
// System.out.println(Student.classRoom);
|
||||
// s1.classRoom = "1903室";
|
||||
|
||||
Student.show();
|
||||
Student.classRoom = "1903室";
|
||||
// System.out.println(s2.classRoom);//"1903室"
|
||||
// System.out.println(Student.classRoom);//"1903室"
|
||||
Student.show();
|
||||
|
||||
}
|
||||
}
|
||||
29
day08/src/com/inmind/static02/Student.java
Normal file
29
day08/src/com/inmind/static02/Student.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.inmind.static02;
|
||||
|
||||
public class Student {
|
||||
//属性(成员变量)
|
||||
int id;
|
||||
int age;
|
||||
String name;
|
||||
|
||||
//静态变量
|
||||
static String classRoom;
|
||||
|
||||
|
||||
//构造方法(无参和有参)
|
||||
|
||||
public Student() {
|
||||
}
|
||||
|
||||
public Student(int id, int age, String name) {
|
||||
this.id = id;
|
||||
this.age = age;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
//(静态方法)
|
||||
public static void show(){
|
||||
String showStr = "该同学在"+classRoom+"教室上课";
|
||||
System.out.println(showStr);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user