在一个子类中使变量为final和static,而在Java中将其保持为变量 [英] Making a variable final and static in one subclass, while keeping it variable in others in Java

查看:95
本文介绍了在一个子类中使变量为final和static,而在Java中将其保持为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类和两个扩展它的子类.我想初始化一个名为radius的变量,该变量可以在子类A中自由设置,但对于子类B始终是相同的.我每次创建对象B时都可以初始化该变量,但是我想知道是否有可能使B子类中的final和static变量,同时仍然能够在我的超类中实现getter.我可能会实现更多具有半径为final或变量的子类.如果不是,我想知道什么是最适合我的问题的解决方案.这是一些有效的示例代码,但是效果不是很好.

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.
    }
}

推荐答案

在一个子类中使变量final和static保持不变 Java中其他变量

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

从技术上讲,您不能这样做. 字段是静态字段或实例字段,不能同时是两者.
或者,在要提供其他值的B类中覆盖getRadius():

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

并且要使此常量受尊重,您还应该在此B类中重写setter:

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

这篇关于在一个子类中使变量为final和static,而在Java中将其保持为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆