繁体   English   中英

来自基本构造函数的Java调用基本方法

[英]Java call base method from base constructor

如何从Super :: Super()调用Super :: printThree?
在下面的示例中,我改为调用Test :: printThree。

class Super {
        Super() { 
        printThree(); // I want Super::printThree here!
        }
        void printThree() { System.out.println("three"); }
}
class Test extends Super {
        int three = 3
        public static void main(String[] args) {
                Test t = new Test();
                t.printThree();
        }
        void printThree() { System.out.println(three); }
}

output:
0    //Test::printThree from Super::Super()
3    //Test::printThree from t.printThree()

您不能-它是子类中已重写的方法; 您不能强制执行非虚拟方法调用。 如果要非虚拟地调用方法,请将该方法设为私有或最终方法。

通常,正是出于这个原因,在构造函数内调用非最终方法是一个坏主意-子类构造函数主体尚未执行,因此您实际上是在尚未完全实现的环境中调用方法初始化。

您在这里违反了动态调度和继承的整个思想。 只是不要这样做(而且无论如何都很难绕过Java)。 而是将函数设为私有和/或最终函数,以使其在继承的类中不会被覆盖

如果Super需要确保不重写printThree()则需要将该方法声明为final 或者,如果选择以下选项,则Test的重写方法可以决定调用重写方法:

@Override
void printThree() { super.printThree(); }

如果基类未将方法标记为final ,则它放弃不让派生类覆盖它并按需进行操作的权利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM