// 显示构造器
public Shop(String name) {
this.name = name;
}
// 成员属性
public String name;
public int tickets = 100;
// 成员方法
public void sale() {
this.
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
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张!
1.2.2、内存分布闵行区售票厅剩余票数:99张!
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();



