覆盖构造函数 [英] Overriding Constructors

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

问题描述

我对Overriding Constructors非常困惑。构造函数不能被覆盖是我在谷歌搜索它时得到的结果我的问题是

I am greatly confused with Overriding Constructors. Constructor can not be overridden is the result what i get when i searched it in google my question is

public class constructorOverridden {

    public static void main(String args[]) {
        Sub sub = new Sub();
        sub.test();
    }
}

class Super {
    Super() {
        System.out.println("In Super constructor");
        test();
    }

    void test() {
        System.out.println("In Super.test()");
    }
}

class Sub extends Super {
    Sub() {
        System.out.println("In Sub constructor");
    }

    void test() { // overrides test() in Super
        System.out.println("In Sub.test()");
    }
}

当我运行这个时我得到了结果

when i run this i got the result as

In Super constructor
In Sub.test()
In Sub constructor
In Sub.test()

请注意子类中的测试方法已执行。是否显示超级构造函数被覆盖。是否正确?

pls note the test method in subclass is executed. Is it shows that Superclass constructor is overridden. Whether is it correct ?

推荐答案

构造函数不是多态的 - 你不能覆盖它们所有。您在子类中创建 new 构造函数,并且每个子类构造函数必须链接(可能是间接)到超类构造函数。如果没有显式链接到构造函数,则会在子类构造函数体的开头插入对无参数超类构造函数的隐式调用。

Constructors aren't polymorphic - you don't override them at all. You create new constructors in the subclass, and each subclass constructor must chain (possibly indirectly) to a superclass constructor. If you don't explicitly chain to a constructor, an implicit call to the parameterless superclass constructor is inserted at the start of the subclass constructor body.

现在就覆盖而言方法 - 一个对象从一开始就是它的最终类型,包括执行超类构造函数时。因此,如果您在超级构造函数代码中打印 getClass(),您仍会看到输出中的Sub 。结果是被覆盖的方法(即 Sub.test )被调用,即使 Sub 构造函数没有'尚未执行。

Now in terms of overriding methods - an object is of its "final type" right from the start, including when executing a superclass constructor. So if you print getClass() in the Super constructor code, you'll still see Sub in the output. The upshot of that is the overridden method (i.e. Sub.test) is called, even though the Sub constructor hasn't yet executed.

这基本上是一个坏主意,你应该几乎总是避免在构造函数中调用可能被覆盖的方法 - 或者非常清楚情况就是这样(因此子类代码知道它不能依赖已经适当初始化的变量等)。

This is fundamentally a bad idea, and you should almost always avoid calling potentially-overridden methods in constructors - or document very clearly that it's going to be the case (so that the subclass code is aware that it can't rely on variables having been initialized appropriately etc).

这篇关于覆盖构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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