Search code examples
javastaticsubclassfinalsuperclass

Making a variable final and static in one subclass, while keeping it variable in others in Java


I have a superclass and two subclasses that extend it. I'd like to initialize a variable called radius which can be set freely in subclass A, but is always the same for subclass B. I could initialize the variable every time I create an object B, but I was wondering if it's possible to make the variable final and static in subclass B, while still being able to implement a getter in my superclass. I might implement more subclasses which have a radius that's either final or variable. If not I'm wondering what would be the most elegant solution for my problem. Here is some sample code which works, but isn't very great.

abstract class SuperClass {

    public double getRadius() {
        return this.radius;
    }

    protected double radius;
}

class A extends SuperClass{

    public void setRadius(double radius) { // Would like to put this setter in SuperClass for future subclasses.
        this.radius = radius;
    }
}

class B extends SuperClass{
    public B() {
        radius = 0.2; //Want to make this static and final only for this subclass.
    }
}

Solution

  • Making a variable final and static in one subclass, while keeping it variable in others in Java

    Technically, you cannot do it. A field is either a static field or an instance field, not both.
    As alternative, override getRadius() in the B class where you want to provide a different value :

    @Override
    public double getRadius() {
        return 0.2;
    }
    

    And to make this constant respected, you should also override the setter in this B class:

    @Override
    public void setRadius(double radius) {   
       throw new UnsupportedOperationException();
    }