目录
1、学习资源1
相关视频:https://www.bilibili.com/video/av52528232/
静态变量作用在成员变量上
1.1、举例:售票。成员变量
1.1.1、普通的成员变量
/**
* 售票厅类
*/
public class Shop {
// 显示构造器
public Shop(String name) {
this.name = name;
}
// 成员属性
public String name;
public int tickets = 100;
// 成员方法
public void sale() {
this.tickets--;
System.out.println(this.name + "售票厅售出1张票!");
show();
}
public void show() {
System.out.println(this.name + "售票厅剩余票数:" + this.tickets + "张!");
}
}
public class Client {
public static void main(String[] args) {
// 实例化对象
Shop s1 = new Shop("徐汇区");
Shop s2 = new Shop("闵行区");
s1.sale();
s2.show();
}
}
打印:
徐汇区售票厅售出1张票!
徐汇区售票厅剩余票数:99张!
闵行区售票厅剩余票数:100张!
这种结果是不行的,因为闵行区的剩余票数与实际结果不符,这是因为s1和 s2有各自的成员变量tickets,互不相关。接下来看一下内存分布。
1.1.2、内存分布
static修饰符
- 作用在成员属性:静态变量
- 作用在成员方法:静态方法
1.2、使用静态变量
1.2.1、静态变量
/**
* 售票厅类
*/
public class Shop {
// 显示构造器
public Shop(String name) {
this.name = name;
}
// 成员属性
public String name;
// 静态变量
public static int tickets = 100;
// 成员方法
public void sale() {
tickets--;
System.out.println(this.name + "售票厅售出1张票!");
show();
}
public void show() {
System.out.println(this.name + "售票厅剩余票数:" + tickets + "张!");
}
}
打印:
徐汇区售票厅售出1张票!
徐汇区售票厅剩余票数:99张!
闵行区售票厅剩余票数:99张!
1.2.2、内存分布
1.3、概念
- 1、成员属性是属于对象的,静态变量是属于类的。
- 2、静态变量的访问,使用:类名.静态变量。例如,Shop.tickets。
- 3、成员属性是在对象被实例化时创建,静态变量是在ClassLoader类型加载器加载类时被创建。
静态变量作用在成员方法上
2.1、代码
/**
* 售票厅类
*/
public class Shop {
// 显示构造器
public Shop(String name) {
this.name = name;
}
// 成员属性
public String name;
// 静态变量
public static int tickets = 100;
// 成员方法
public void sale() {
tickets--;
System.out.println(this.name + "售票厅售出1张票!");
show();
}
//静态方法
public static void show() {
System.out.println("系统剩余票数:" + tickets + "张!");
}
}
public class Client {
public static void main(String[] args) {
// 实例化对象
// Shop s1 = new Shop("徐汇区");
// Shop s2 = new Shop("闵行区");
//
// s1.sale();
// s2.show();
Shop.show();
}
}
2.2、概念
静态方法中只能访问静态变量或者静态方法,不能访问成员变量或者成员方法
2、学习资源2
static关键字定义在类的名字上(普通类不允许static修饰,只有内部类可以),静态内部类和它得外部类没有任何关系,完全可以写在外部作为一个单独的类