Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Constants in Java

Tags:

I have two classes that extend the same abstract class. They both need the same constant, but with different values. How can I do this? Some example code to show what I want to do.

abstract class A {    public static int CONST; }  public class B extends A {    public static int CONST = 1; }  public class C extends A {    public static int CONST = 2; }  public static void main(String[] args){     A a = new B();     System.out.println(a.CONST); // should print 1 } 

The above code does not compile because CONST is not initialized int class A. How can I make it work? The value of CONST should be 1 for all instances of B, and 2 for all instances of C, and 1 or 2 for all instances of A. Is there any way to use statics for this?

like image 526
Fractaly Avatar asked Dec 11 '11 21:12

Fractaly


People also ask

Can you override a constant?

The same applies when constants are defined as final in an abstract classes, or interface; they can't be overridden by classes extending that abstract or implementing that interface. So class and interface constants can now truly become constant.

Can constants be changed in Java?

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants, but the variable modifiers static and final can be used to effectively create one.

Can we override attributes in Java?

In short, no, there is no way to override a class variable. You do not override class variables in Java you hide them. Overriding is for instance methods.

Can we override final variable in Java?

No, the Methods that are declared as final cannot be Overridden or hidden.


2 Answers

You can't do that.

You can do this, however:

abstract class A {    public abstract int getConst(); }  public class B extends A {    @Override    public int getConst() { return 1; } }  public class C extends A {    @Override    public int getConst() { return 2; } }  public static void main(String[] args){     A a = new B();     System.out.println(a.getConst()); } 
like image 189
Oliver Charlesworth Avatar answered Sep 27 '22 22:09

Oliver Charlesworth


If a constant has a variable value, it's not a constant anymore. Static fields and methods are not polymorphic. You need to use a public method to do what you want.

like image 34
JB Nizet Avatar answered Sep 27 '22 22:09

JB Nizet