user1748526
user1748526

Reputation: 464

Change a final field in Java

I have something like this:

class A {
    final int f = 1;
    int getF() {
        return f;
    }
}

class B extends A {}

Is it possible to call getF() in B class, and get 0 from it? Can this final field has another value from 1? Cause I get 0 result from getF() sometimes and have no idea what happens. No overrides or something. Just calling getF() and getting 0. In some situations. Can somebody guess why can it be like this?

Upvotes: 1

Views: 173

Answers (4)

BevynQ
BevynQ

Reputation: 8254

There is not legitimate way for 0 to be returned, from the information you have provided. However there are semi-legitimate and other hacky ways for it to happen. What you will need to do to diagnose this problem is to put conditional stop points on the code where you see the 0 being returned. I suspect the structure that is present is not the one you expect, the debugger should show you the structure and why the value is 0.

Upvotes: 0

sathish_at_madison
sathish_at_madison

Reputation: 833

Is this what you are looking for??

public class A {

final int f = 1;

int getF() {
    return f;
 }
}

public class B extends A {
public int getF() {
    return f;
}

public void setF(int f) {
    this.f = f;
}

int f;
public B(){
 f=0;
}
public static void main(String args[]) {
    B a = new B();
    System.out.println(a.getF());
  }
}

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122414

The only combination of circumstances that I can think would allow this would be if there is another class above A that declares a method which is called by its constructor, and B overrides that method and calls getF from within there

class Super {
  public Super() {
    doInit();
  }

  protected void doInit() { /* ... */ }
}

class A extends Super {
  // f and getF as before
}

class B extends A {
  protected void doInit() {
    System.out.println(getF());
  }
}

Or similarly if the constructor "leaks" a this reference to somewhere where it can be accessed before the constructor has finished running, thus breaking the usual immutability guarantees of finals.

Upvotes: 3

erickson
erickson

Reputation: 269857

With only the code as given, no, it's not possible to get anything but 1 from getF(). I suspect there is more to the story. For example, if you override getF(), either in B or a subclass of B, you could get different results.

Upvotes: 1

Related Questions