简体   繁体   中英

Assigning String to a final String

I have a few classes like this:

public class A {
    private String foo;

    public A(String f) {
        foo = f; // I want foo to be final based on the subclass instance
    }
}

public class B extends A {
    private static final String FOO = "foo1";

    public B() {
        super(FOO);
    }
}

public class C extends A {
    private static final String = "foo2";

    public C() {
        super(FOO);
    }
}

What I want is when I create an object on type B , I don't want the String in A to be changeable. foo = f just assigns a reference but I want foo to be the same final object FOO . How can I do this?

It appears you don't want a field at all, instead you can have a method.

interface A {
    String foo(); // the implementation depends on the sub-class.
}

class B implements A {
    public String foo() { return "foo1"; }
}

class C implements A {
    public String foo() { return "foo2"; }
}

This is maybe not the best in design but what you want to do is to initialize a final String.

public class A {
    private final String foo;

    public A(String f) {
        foo = f; 
    }
}

Final variables can be initialized only once, so you can initialize it in the constructor. But in your case that doesn't make sense because your subclasses are not able to access foo because it is private. See here for all available Java visibility modifiers.

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