本文介绍了Java从基构造函数调用基方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to call Super::printThree from Super::Super()?
In the example below I call Test::printThree instead.

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

推荐答案

你不能 - 这是一个在子类中被覆盖的方法;你不能强制非虚方法调用.如果您想以非虚拟方式调用方法,请将方法设为私有或最终.

You can't - it's a method which has been overridden in the subclass; you can't force a non-virtual method call. If you want to call a method non-virtually, either make the method private or final.

一般来说,正是出于这个原因,在构造函数中调用非最终方法是一个坏主意——子类构造函数体还没有被执行,所以你在一个没有执行的环境中有效地调用了一个方法t 已完全初始化.

In general it's a bad idea to call a non-final method within a constructor for precisely this reason - the subclass constructor body won't have been executed yet, so you're effectively calling a method in an environment which hasn't been fully initialized.

这篇关于Java从基构造函数调用基方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:22
查看更多