在java中覆盖静态的替代方法 [英] Alternative to overiding static in java

查看:43
本文介绍了在java中覆盖静态的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道:将属性拟合到属于大型继承结构的类的最佳方法是什么.我想创建一个抽象的静态方法,每个类都会覆盖该方法,但是经过一个似乎不起作用的快速谷歌.有什么建议?

我可以把它变成一个实例方法,但它确实是一个类级别的规范.

提前致谢.

解决方案

我建议你创建一个抽象方法,就像你想到的那样,让这个方法在每个类的静态变量中实现.

>

抽象类 Base {抽象字符串 getValue();}A 类扩展 Base {静态字符串 aValue = "来自 A";字符串 getValue() {返回一个值;}}B 类扩展 A {静态字符串 bValue = "来自 B";字符串 getValue() {返回 b 值;}}

它需要在每个类中多一点样板,而不仅仅是一个字段声明,但我相信很难做任何事情.

I was wondering: what would be the best way to fit an attribute to a class which is part of a large inheritance structure. I wanted to make an abstract static method which each class would override but after a quick google that doesn't seem to work. Any suggestions?

I could make it an instance method but it really is a class level specification.

Thanks in advance.

解决方案

I would suggest you create an abstract method, just as you have thought of, and let this method be implemented in terms of static variables in each class.

abstract class Base {
    abstract String getValue();
}

class A extends Base {

    static String aValue = "From A";

    String getValue() {
        return aValue;
    }
}

class B extends A {

    static String bValue = "From B";

    String getValue() {
        return bValue;
    }
}

It requires a little bit more boiler plate in each class, than just a field declaration, but I believe it is hard to do anything about that.

这篇关于在java中覆盖静态的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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