Initialize a static final variable in a child class (subclass) in java

I have a class like this:

public abstract class A {
    public static final int FIELD;
    // some methods
}

and I want to initialize the FIELD variable in the child class. I mean something like this:

public class B extends A {
    FIELD = 5;
}

EDIT I actually have several classes that extend A, and they all have a FIELD variable, but with different values; so I found to reorganize the FIELD variable and declare it in a superclass. are there any other solutions? is it possible to have something like this? thanks for the help.

+4
source share
7 answers

, , , , ; , . FIELD .
@LenceJava . @LanceJava.

+2

static final, / . .

+1

B, A, ; .

+1

, ( , - )

A. A B. , B, , B .

, , A.FIELD B?

, , , , B.

, , , .

0

final , . final java . .

0

, .

1) Delete the final keyword for the FIELD attribute

2) Change the code as follows

import java.io.*;
import java.util.*;

class A {
    public static int FIELD = 4;
}
class B extends A {
    public B(){
        this.FIELD  = 5;
    }
}
public class Test {

    public static void main(String args[]) throws Exception {
    B b = new B();
        System.out.println("B value:"+b.FIELD);
    }

}

Exit:

B value:5
0
source

That should work.

public class A {
public final int FIELD;
A(int a){
this.FIELD=a;
}
}
public class B extends A {
B(int a){
super(a);
}
}
-2
source

All Articles