基础构造函数的Java调用基方法 [英] Java call base method from base constructor

查看:249
本文介绍了基础构造函数的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.

一般来说,在构造函数中调用非final方法是个坏主意。正是由于这个原因 - 子类构造函数体还没有被执行,所以你在一个尚未完全初始化的环境中有效地调用了一个方法。

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调用基方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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