📄 staticdemo.java
字号:
class StaticDemo {
static int x; //定义静态变量x
int y; //定义实例变量y
static public int getX() { //定义静态方法getX
return x;
}
static public void setX(int newX){ //定义静态方法setX
x=newX;
}
public int getY() { //定义实例方法getY
return y;
}
public void setY(int newY){ //定义实例方法setY
y=newY;
}
}
class ShowDemo{
public static void main(String args[]){
System.out.println("静态变量x="+StaticDemo.getX()); //静态方法的引用可以使用类名
//System.out.println("实例变量y="+StaticDemo.getY());非法,编译时将出错
StaticDemo a=new StaticDemo();
StaticDemo b=new StaticDemo();
a.setX(1);
a.setY(2);
b.setX(3);//对象a和b中的x共享同一个存储区域,在同一时刻x值是一样
b.setY(4);//对象a和b中变量Y有着不同存储区域,可以有不同的值
System.out .println("静态变量a.x=" +a.getX());
System.out .println("实例变量a.x=" +a.getY());
System.out .println("静态变量b.x="+b.getX());
System.out .println("实例变量b.y="+b.getY());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -