英文:
Java Constants inheritance
问题
我注意到我可以这样做:
public class Message {
public static final int MIN_BYTES = 5;
}
...并且将这个类作为另一个类的父类,并设置相同的常量为另一个值,例如:
public class Ack extends Message {
public static final int MIN_BYTES = 1;
}
由于编译器没有报错,这引发了我上面的问题:
- 这些变量真的是相同的吗?
- 我会说它选择最具体的值,所以在这种情况下是从Ack类中获取。这是真的吗?
- 常量不能更改它们的值(它是final的),所以如果问题1是真的,那么这是怎么可能的呢?
谢谢!
英文:
I noticed I can do:
public class Message {
public static final int MIN_BYTES = 5;
}
...and set this class as parent of another and set the same constant with another value like:
public class Ack extends Message {
public static final int MIN_BYTES = 1;
}
Since compiler does not complaing, this lead me to the questions above:
- Are these variables really the same?
- I would say it gets the most specific, so in that case from the Ack class. Is that true?
- Constants cannot have their value changed (it is final), so if the question 1 is true, how is that possible?
Thanks!
答案1
得分: 4
- No.
Ack.MIN_BYTES
andMessage.MIN_BYTES
have no relationship to each other. - It's not clear what you're asking -- what gets the most specific?
a.MIN_VALUE
depends on the static type ofa
-- if you writeMessage a = new Ack()
, thena.MIN_VALUE
will give youMessage.MIN_BYTES = 5
. If you writeAck a = new Ack()
, thena.MIN_VALUE
will give youAck.MIN_BYTES = 1
. - Not applicable.
英文:
- No.
Ack.MIN_BYTES
andMessage.MIN_BYTES
have no relationship to each other. - It's not clear what you're asking -- what gets the most specific?
a.MIN_VALUE
depends on the static type ofa
-- if you writeMessage a = new Ack()
, thena.MIN_VALUE
will give youMessage.MIN_BYTES = 5
. If you writeAck a = new Ack()
, thena.MIN_VALUE
will give youAck.MIN_BYTES = 1
. - Not applicable.
答案2
得分: 1
第二个不会覆盖第一个。它只是将其隐藏在Ack
内。所有声明为public static final
的类成员可以使用[fullpackagename].[classname].[variablename]
来访问。
英文:
The second does not overwrite the first. It just hides it within Ack
. ALL class members declared public static final
can be accessed using [fullpackagename].[classname].[variablename]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论