有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

继承java在派生构造函数中调用超级构造函数,与设置字段值完全相同?

在java中定义派生类的构造函数有两种方法

DerivedClassWithSuper中,我使用super()函数来定义构造函数。 但是,在DerivedClassWithoutSuper中,我不使用super()函数来定义构造函数

我想知道的一件事是,它们之间有什么区别吗

我也知道DerivedClassWithSuper的代码看起来更好,但我不确定在DerivedClassWithoutSuper中定义构造函数时是否有任何副作用

class BaseClass {
    int id;
    BaseClass () {
        this.id = 0;
        System.out.printf("Base class is created, id: %d \n", this.id);
    }
}

class DerivedClassWithSuper extends BaseClass {
    String name;
    DerivedClassWithSuper () {
        super(); 
        // this.id = 0;
        this.name = "Unknown";
        System.out.printf("DerivedClassWithSuper is created, this.id: %d, name: %s\n", this.id, this.name);
    }
}

class DerivedClassWithoutSuper extends BaseClass {
    String name;
    DerivedClassWithoutSuper () {
        this.id = 0;
        this.name = "Unknown";
        System.out.printf("DerivedClassWithoutSuper is created, id: %d, name: %s\n", this.id, this.name);
    }
}

我一直感谢你的帮助。谢谢


其他问题: 如果没有super()函数,则派生类隐式调用super()

在下面稍加修改的代码中,在DerivedClassWithoutSuper构造函数中将this.id设置为10,并隐式调用super()函数。如果调用super(),则this.idsuper.id应设置为0

但是,super.idthis.id是10

我不明白为什么会这样

class BaseClass {
    int id;
    BaseClass () {
        this.id = 0;
        System.out.printf("Base class is created, id: %d \n", this.id);
    }
}

class DerivedClassWithSuper extends BaseClass {
    String name;
    DerivedClassWithSuper () {
        super();
        this.name = "Unknown";
        System.out.printf("DerivedClassWithSuper is created");
        System.out.printf("%d %d\n", this.id, super.id);
    }
}

class DerivedClassWithoutSuper extends BaseClass {
    String name;
    DerivedClassWithoutSuper () {
        // if super() implicitly called?
        this.id = 10;
        this.name = "Unknown";
        System.out.printf("DerivedClassWithoutSuper is created\n");
        // then this.id and super.id should be different. 
        // but, both are 10 as set in this constructor. 
        System.out.printf("%d %d\n", this.id, super.id);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    如果子类构造函数没有显式地调用super(...)(或this(...)),编译器将隐式地为您调用no-arg super()构造函数。如果不存在这样的构造函数,编译将失败,即使您从未编写过调用

    参见例如The Java™ Tutorials - Using the Keyword super

    Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.