Jay
Jay

Reputation: 357

How do you redefine a constant variable in a derived class? [JAVA]

Say I have a class

class A {
   public static final int x = 1;
}

and I have a derived class

class B extends A {
   x = 2; // want to redefine x as 2 here
}

How would I go about for redefining the constant as 2 in the derived class B? I recall there being a constructor "trick" when working with C++, but I am lost on what to do in Java. I even tried removing the "final" from the variable declaration in Class A, but Class B doesn't even know X is defined. It says I need to add the "public static final int" in front of the x in Class B, but I thought it was already defined in A.

Upvotes: 0

Views: 4495

Answers (4)

nachokk
nachokk

Reputation: 14413

You can't. Static belong to class not to instances.

But to make a trick you can create another constant with the same name. You access to that constant with

A.x or B.x

class B extends A {
  public static final x = 2;
}

In this example A.x=1 and B.x=2

Or if you want to redefine as you asked you can do this but it's pointless

class B extends A{
  static{
    x=2;// assuming 'x' not final
  }
}

In this example A.x=2 and B.x=2

Upvotes: 3

Jobin Thomas
Jobin Thomas

Reputation: 109

The point of having final is that, no one should be able to change it.

Here is a sample code if you just want to use static:

class Test2{
  public static int a=0; // if you use final here the code will not compile
}

class B extends Test2{
  //a = 1000; - this requires a datatype
  public void setA(){
    a=1000;
    System.out.println(a);
  }
}


class C{
  public static void main(String args[]){
      B objB = new B();
      objB.setA();
  }
}

Upvotes: 0

René Winkler
René Winkler

Reputation: 7058

I f you remove the final keyword, you can assign x in the constructor of B as follows:

  class B extends A {

   public B(){
       A.x = 2;
   }
}

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

It is NOT possible. public static final int is a compile time constant it cannot be re-initialized.

Upvotes: 2

Related Questions