在Java中,静态数据成员会被继承吗?

huangapple go评论68阅读模式
英文:

Is a static data member inherited in Java?

问题

从父类继承的静态变量会原样传递到子类,还是会创建一个新的变量?

例如,如果有一个位于 class Aclass 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.

huangapple
  • 本文由 发表于 2020年9月5日 12:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63750573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定