子类继承父类静态变量问题

java示例:

public class Main7 extends Father{

	//static int test = 11; 
	public static void main(String[] args) {
		test++;
		Father father = new Father();
		System.out.println(test);
	}
}

class Father{
	static int test = 1;
	public Father() {
		System.out.println(test);
	}
}

输出结果:

2
2

去掉注释输出结果:

1
12

分析:

当子类没有重新定义同名属性时,子类父类共享该属性。当子类重新定义时,不共享,是两个不同变量,值不同。

对比普通属性:

public class Main7 extends Father{

	public static void main(String[] args) {
		Father father = new Father();
		Child child = new Child();
		father.test++;
		System.out.println(father.test);
		System.out.println(child.test);
	}
}

class Father{
	int test = 1;
	public Father() {
		System.out.println(test);
	}
}

class Child extends Father{
	public Child() {
		System.out.println(test);
	}
}
输出结果1    1    1    2    1

你可能感兴趣的:(Java)