在Java中,您可以通过父类的子类的构造函数调用父类的超类构造函数吗?

use*_*796 7 java inheritance constructor

我知道措辞有点令人困惑和奇怪,但忍受我,我不知道如何短语,任何更短.

假设你有一个被调用的类SuperBlah,并且你在一个叫做的类中继承了它,Blah然后你继承Blah了一个名为ChildBlah(So SuperBlah-Blah-ChildBlah)的类.super();ChildBlah构造函数中使用的关键字SuperBlah是否Blah会在没有构造函数的情况下调用构造函数?

对于那些拒绝的人,那为什么会这样呢?我们有一个名为BlusterBug的类,它扩展了Critter类,并在BlusterBug的构造函数中调用了super.Critter没有构造函数,但是Critter扩展的Class确实有一个构造函数.(我故意省略了类的其余代码)

public class BlusterCritter extends Critter {
    // instance vaiables
    private int courageFactor;
    private static final double DARKENING_FACTOR = 0.05;
    // create a constructor(include what is necesary for parent)
    public BlusterCritter(int c)
    {
        super();
        courageFactor = c;
    }
Run Code Online (Sandbox Code Playgroud)

然后在Critter类中,它没有任何构造函数!

public class Critter extends Actor// omitted all the code
{
    /**
     * A critter acts by getting a list of other actors, processing that list,
     * getting locations to move to, selecting one of them, and moving to the
     * selected location.
     */
    public void act()
    {
        if (getGrid() == null)
            return;
        ArrayList<Actor> actors = getActors();
        processActors(actors);
        ArrayList<Location> moveLocs = getMoveLocations();
        Location loc = selectMoveLocation(moveLocs);
        makeMove(loc);
    }
Run Code Online (Sandbox Code Playgroud)

但是Actor类有一个构造函数!

public class Actor
{
    private Grid<Actor> grid;
    private Location location;
    private int direction;
    private Color color;

    /**
     * Constructs a blue actor that is facing north.
     */
    public Actor()
    {
        color = Color.BLUE;
        direction = Location.NORTH;
        grid = null;
        location = null;
    }
Run Code Online (Sandbox Code Playgroud)

最奇怪的部分?该程序工作得很好,编译器不会捕获任何错误!这是怎么回事?

ajb*_*ajb 4

如果Blah没有任何构造函数,编译器将生成一个隐式无参数构造函数,即Blahsuper()会调用 的SuperBlah构造函数。

因此,当ChildBlah调用 's 构造函数时super(),它将调用编译器为其生成的隐式构造函数Blah,从而导致SuperBlah调用 's 构造函数。所以从某种意义上说,我认为你的问题的答案是“是”。

但这仅在Blah没有构造函数的情况下才有效。(在您的实际代码中,Critter没有任何构造函数,因此它可以工作。)如果为 定义了任何其他构造函数Blah,但没有可访问的无参数构造函数,则不会有隐式无参数构造函数,并且结果将在编译时出错。