public class Error {
public static void main(String[] args) {
System.out.println(StaticText.x);
System.out.println(StaticText.y);
}
}
class StaticText{
public static StaticText st=new StaticText();//在这个位置答案是1 4
public static int x;
public static int y=4;
//public static StaticText st=new StaticText();//在这个位置答案是1 5
public StaticText() {
x++;
y++;
}
}
//加载和执行
/*
* 加载(加载到静态区赋予初始值) 执行(StaticText st=new StaticText()) 执行(int x) 执行(int y=4)
* st null 0x23ab45(一个地址值) 0x23ab45 0x23ab45
* x 0 1 1 1
* y 0 1 1 4
*/
package cn.day011;
public class A {
public static void main(String[] args) {
System.out.println(ST.x+" "+ST.y); //1 1
}
}
class ST{
static ST st=new ST();//属性
static int x=1;
static int y;
public ST() {
x++;
y++;
}
}
//加载和执行
/*
* 加载(加载到静态区赋予初始值) 执行(StaticText st=new StaticText()) 执行(int x=1) 执行(int y)
* st null 0x23ab45(一个地址值) 0x23ab45 0x23ab45
* x 0 1 1 1
* y 0 1 1 1
* int y只是声明,系统默认值在静态区已经赋值了,所以y执行到static int y ;还是1;
*/
package cn.day011;
public class A {
public static void main(String[] args) {
ST S=new ST();
System.out.println(S.x+" "+S.y); // 2 2
}
}
class ST{
static ST st=new ST();//属性
static int x=1;
static int y;
public ST() {
x++;
y++;
}
}
package cn.day011;
public class A {
public static void main(String[] args) {
System.out.println(new ST().x+" "+new ST().y); // 2 3
}
}
class ST{
static ST st=new ST();//属性
static int x=1;
static int y;
public ST() {
x++;
y++;
}
}
//x比y少加一次
package cn.day011;
public class A {
public static void main(String[] args) {
ST S=new ST();
System.out.println(S.x+" "+S.y); //栈溢出错误
}
}
class ST{
ST st=new ST();//属性
static int x=1;
static int y;
public ST() {
x++;
y++;
}
}
//等同于在堆中不断的开辟新空间,在栈中不断的开辟空间存放变量,因为栈远远小于堆所以栈溢出
//那么为什么加上static 不报错,因为static 只加载一次,空间也是开辟一次