Fractaly
Fractaly

Reputation: 833

Overriding Constants in Java

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?

Upvotes: 22

Views: 22003

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272527

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

Upvotes: 25

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 6

Related Questions