Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Constants inheritance [duplicate]

Tags:

java

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!

like image 872
Felipe C. Avatar asked Aug 14 '20 20:08

Felipe C.


Video Answer


2 Answers

  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.
like image 75
Louis Wasserman Avatar answered Sep 22 '22 01:09

Louis Wasserman


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]

like image 22
ControlAltDel Avatar answered Sep 23 '22 01:09

ControlAltDel