英文:
Is a static data member inherited in Java?
问题
从父类继承的静态变量会原样传递到子类,还是会创建一个新的变量?
例如,如果有一个位于 class A
和 class B extends A
的静态计数器变量,是否会给予相同的值(如果我们没有为 class B
定义新的计数器)?
英文:
Will a static variable from the parent class be inherited as is to the child class, or will a new variable be created?
For example, should a static counter variable of class A
and class B extends A
give the same value (if we have not defined a new counter for class B
) ?
答案1
得分: 0
不,静态变量的行为不像非静态变量。如果您使用一个继承类更改静态变量的值,它将影响所有其他继承类的数据。
因为静态变量只创建一次。即使您创建多个对象,静态变量也不会一次又一次地创建。它们在执行的起始时间创建并存储。每当访问静态变量时,您都将获得相同的变量。
也就是说,
如果您以 B.count 或 C.count 的方式访问,您将获得相同的变量。
因此,您只有一个变量,那么您无法在单个变量中分别维护两个对象的计数。
英文:
No, Static variable does not behave like non-static variables. If you change value of static variable with one of the inherited class it will effect all other inherited class data.
Cause static variable is created only once. Even though you are creating multiple objects the static variables are not created again and again. They are created at starting time of execution and stored. When ever you access static variable you will get same variable.
i.e
if you are accessing as B.count or C.count you will get same variable.
So you are having only one variable then you can't maintain count separately for two objects in single variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论