简体   繁体   中英

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?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM