java 覆盖构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14643362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:56:20  来源:igfitidea点击:

Overriding Constructors

javaoop

提问by Hymanyesind

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 ?

请注意子类中的测试方法被执行。它是否表明超类构造函数被覆盖。是否正确?

回答by Jon Skeet

Constructors aren't polymorphic - you don't overridethem at all. You create newconstructors 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.

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

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 Superconstructor code, you'll still see Subin the output. The upshot of that is the overridden method (i.e. Sub.test) is called, even though the Subconstructor hasn't yet executed.

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

This is fundamentally a bad idea, and you should almost always avoid calling potentially-overridden methods in constructors - or document very clearlythat 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).

这从根本上来说是一个坏主意,您几乎总是应该避免在构造函数中调用可能被覆盖的方法 - 或者非常清楚地记录这种情况(以便子类代码知道它不能依赖已被覆盖的变量)适当初始化等)。

回答by Audrius Meskauskas

You cannot override the constructor as the constructor is invoked by the name of the class it constructs. How can you create some different class with the same constructor? Also, a child class does not inherit constructors from its parent.

您不能覆盖构造函数,因为构造函数是由它构造的类的名称调用的。如何使用相同的构造函数创建一些不同的类?此外,子类不会从其父类继承构造函数。

If the parent constructor does some important initialization, it can be called from the child constructor using super:

如果父构造函数进行了一些重要的初始化,则可以使用 super 从子构造函数调用它:

class Err extends Throwable {
   Err(String message) {
       super(message); // Call the constructor of Throwable.
        ..

The parent class constructor is also always called. If you yourself do not call any, a constructor without parameters is called automatically before entering a constructor of the derived class. If the parent has no parameterless constructor and you do not call any, a compile time error is reported.

父类构造函数也总是被调用。如果您自己不调用 any,则在进入派生类的构造函数之前会自动调用一个没有参数的构造函数。如果父级没有无参数构造函数并且您没有调用任何构造函数,则会报告编译时错误。

回答by toasted_flakes

The first implicit line of a constructor is a call to Super(). That's why you get those results.

构造函数的第一行隐式是对 的调用Super()。这就是为什么你会得到这些结果。

回答by Brian Agnew

That's correct. When instantiating a subclass, the superclass constructor is called first, and then each successive constructor in the hierarchy.

没错。实例化子类时,首先调用超类构造函数,然后调用层次结构中的每个后续构造函数。

In your example above, the superclass constructor calls an overridden method (test()). This works, but is potentially dangerous since the subclass constructor has not been called, and your subclass will not have been fully initialised. For this reason calling overridden (or overriddable) methods in a constructor is not good practise.

在上面的示例中,超类构造函数调用了一个重写方法 ( test())。这有效,但由于尚未调用子类构造函数,并且您的子类尚未完全初始化,因此存在潜在危险。出于这个原因,在构造函数中调用覆盖(或可覆盖)方法不是好的做法。

回答by Subhrajyoti Majumder

it is not overriding super class constructor and constructor can not be overridden it can be overloaded.

它不会覆盖超类构造函数,并且构造函数不能被覆盖,它可以被重载。

When you create child class object super class will be instantiated first then sub class will be instantiated. Its like Child can not be existed without parent.

当您创建子类对象时,将首先实例化超类,然后实例化子类。就像孩子不能没有父母一样存在

Compiler will automatically call super class constructor from sub class constructor .

编译器会自动从子类构造函数调用超类构造函数。

Sub() {
    super();
    System.out.println("In Sub constructor");
}