package oo.day05;
//static演示
public class StaticDemo {
public static void main(String[] args) {
Joo o1 = new Joo();
o1.show(); //a=1,b=1
Joo o2 = new Joo();
o2.show(); //a=1,b=2

System.out.println(Joo.b); //建议通过类名点来访问
System.out.println(o1.b); //不建议

Koo.test(); //静态方法常常通过类名点来访问

Loo o3 = new Loo();
Loo o4 = new Loo();
Loo o5 = new Loo();

}
}

class Loo{
static{ //因为类只被加载一次,所以静态块也只执行一次
System.out.println("静态块");
}
Loo(){
System.out.println("构造方法");
}
}

 

class Koo{
int a; //实例变量,对象点来访问
static int b; //静态变量,类名点来访问
void show(){ //隐式传递this
this.a = 1;
b = 2;
}
static void test(){ //没有隐式this传递
//a = 1; //没有this意味着没有对象,没有对象意味着不能访问实例成员,因为实例成员需要由对象点来访问
b = 2;
}
}

 


class Joo{
int a; //实例变量:属于对象的,存在堆中,有一个对象就有一份
static int b; //静态变量:属于类的,存在方法区中,只有一份
Joo(){
a++;
b++;
}
void show(){
System.out.println("a="+a);
System.out.println("b="+b);
}
}

 

 

 静态修饰词static以及图解分析

 

相关文章:

  • 2022-01-05
  • 2022-12-23
  • 2021-08-17
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-11-23
  • 2021-07-18
猜你喜欢
  • 2021-10-08
  • 2021-12-26
  • 2021-10-03
  • 2021-10-19
  • 2021-09-30
  • 2022-12-23
相关资源
相似解决方案