Blog Layout

Overriding constants in Java

John Dalsgaard • sep. 03, 2015

If you are like me then you really want to minimize duplication of code and reuse as much as possible. A common use case that has caused me trouble is this scenario where I have a common function that uses some context (in the form of constants). For a particular subclass I just need to redefine the constant to make everything behave like I want. Something like this:


public class Base {
protected final static String letter = "-";
protected void print1(){
System.out.println("Letter=" + letter);
}
}

public class A extends Base {
protected static String letter = "A";
}

And called like this:
A a = new A();
a.print1();


I had expected to see "A" as the output from above - but no, it is "-"...


Basically, what happens is that you define a new variable in a different scope - instead of overriding the existing constant/variable... And when you think about it I suppose it is quite natural. But then how can one get around this - and keep the basic idea of what I was trying to obtain? Well, you simple use a getter - and override that. So if you do this instead:


public class Base {
protected final static String letter = "-";
protected String getLetter(){
return letter;
}
protected void print2(){
System.out.println("Letter=" + getLetter());
}
}public class A extends Base {
protected static String letter = "A";
protected String getLetter(){
return letter;
}
}And called like this:
A a = new A();
a.print2();


... then you get the expected "A" from the method defined in the Base class but called in the subclass A.


Perhaps very simple - but it took me a little effort to understand that I could not just override the constant/variable and had to change the approach slightly.


Happy coding!!


Blog

Af John Dalsgaard 17 Mar, 2023
Dalsgaard Data A/S celebrates 25 years!
25 års jubilæum
Af John Dalsgaard 17 Mar, 2023
Dalsgaard Data A/S fylder 25 år!
Flere indlæg
Share by: