开发者

defer final value to subclass java

开发者 https://www.devze.com 2023-03-25 05:25 出处:网络
I have a question similar to In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around? but which requires a di

I have a question similar to In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around? but which requires a different solution. As in the above case, I want to declare a variable to开发者_StackOverflow be Final in the superclass, but I want the subclass to give it the value. What makes my problem different though is that I don't want the value passed in to the subclass, I want the subclass to 'know' its value, so the above solution doesn't work for me. Then I tried to do this:

public class Superclass{
    public final int x;
    public Superclass(int x){
        this.x = x;
    }
}
public class Subclass extends Superclass{
    public Subclass(){
        x = 1;
        super(x);
    }
}

...which didn't work (the call to super() must be on the first line :/ ). But this is basically the behavior that I want. Is there a good way to do this? Thanks!


You could do

super(1);

so instead of setting x, you are passing the value.


An alternative to the one above:

class Superclass{
    public final int x;

    public Superclass(int x){
        this.x = x;
    }

    public static Superclass createNew(Integer y) {
        return new Superclass(y);
    }

    public void print() {
        System.out.println(this.x);
    }
}
class Subclass extends Superclass{
    public Subclass(int x) {
        super(process(x));
    }

    public static Integer process(Integer y) {
        if (y < 100)
            y += 100;
        return y;
    }
}


I don't have a java compiler handy, but you're attempting to set x = 1 twice in this code.

x = 1;

And

super(x); //==> this.x = x 

Do as @Kal said and do super(1), as x = 1 won't work.

0

精彩评论

暂无评论...
验证码 换一张
取 消