阅读640 返回首页    go 阿里云 go 技术社区[云栖]


【JAVA】类继承对父类静态变量的操作

对静态变量的操作存在继承时还是有一些模糊,做了个简单的测试:

class Test
{
	private String mName;

	public Test(String name) {
		setName(name);
	}

	public void setName(String name) {
		mName = name;
	}

	public String getName() {
		System.out.println(mName);
		return mName;
	}
}

class A {
	protected static String TAG = "A";
	protected static Test mTest;

	public A() {
		
	}

	public Test getTest() {
		return mTest;
	}
}

class B extends A
{
	protected static String TAG = "B";

	public B() {
		mTest = new Test(TAG);
	}
}

class C extends A
{
	protected static String TAG = "C";

	public C() {
		mTest = new Test(TAG);
	}
}

public class Demo
{
	public static void main(String[] args) {
		B b = new B();
		C c = new C();
		b.getTest().getName(); // print C
		c.getTest().getName(); // print C
    }
}


JAVA 中如果继承的父类中存在静态变量,多个子类操作的还是同一个静态变量地址,因此子类的操作是要相互覆盖的。

如果子类重写了父类的方法和静态变量则专属子类了,其它子类的操作也就不会相互覆盖了。




最后更新:2017-04-03 12:55:50

  上一篇:go Interop type 'Microsoft.Office.Interop.Word.ApplicationClass' cannot be embedded. Use the applicable
  下一篇:go Flume-ng出现HDFS IO error,Callable timed out异常