5

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!

Felipe C.
  • 97
  • 6
  • 2
    These are two separated static fields, existing individually. You cannot override static members. – Progman Aug 14 '20 at 20:25

2 Answers2

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.
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

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]

wovano
  • 4,543
  • 5
  • 22
  • 49
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80