Java常量继承

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

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;
}

由于编译器没有报错,这引发了我上面的问题:

  1. 这些变量真的是相同的吗?
  2. 我会说它选择最具体的值,所以在这种情况下是从Ack类中获取。这是真的吗?
  3. 常量不能更改它们的值(它是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:

  1. Are these variables really the same?
  2. I would say it gets the most specific, so in that case from the Ack class. Is that true?
  3. Constants cannot have their value changed (it is final), so if the question 1 is true, how is that possible?

Thanks!

答案1

得分: 4

  1. No. Ack.MIN_BYTES and Message.MIN_BYTES have no relationship to each other.
  2. It's not clear what you're asking -- what gets the most specific? a.MIN_VALUE depends on the static type of a -- if you write Message a = new Ack(), then a.MIN_VALUE will give you Message.MIN_BYTES = 5. If you write Ack a = new Ack(), then a.MIN_VALUE will give you Ack.MIN_BYTES = 1.
  3. Not applicable.
英文:
  1. No. Ack.MIN_BYTES and Message.MIN_BYTES have no relationship to each other.
  2. It's not clear what you're asking -- what gets the most specific? a.MIN_VALUE depends on the static type of a -- if you write Message a = new Ack(), then a.MIN_VALUE will give you Message.MIN_BYTES = 5. If you write Ack a = new Ack(), then a.MIN_VALUE will give you Ack.MIN_BYTES = 1.
  3. 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]

huangapple
  • 本文由 发表于 2020年8月15日 04:21:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63419554.html
匿名

发表评论

匿名网友

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

确定