java - 调用对象的构造函数

标签 java constructor

  1. 当类已经有参数化构造函数和非参数化构造函数时,为什么类应该调用 Objects 类的默认构造函数?

示例

public abstract class Foo{
    private int dim1;

    public Foo(int dim1) {
        super();
        this.dim1 = dim1;

    }
    public Foo() {

        this.dim1 = 0;

    }
}

2.为什么上例中的非参数化构造函数中没有调用 super() 方法?

  • 如果我忘记或者不想使用 super() 调用 Object 类中的构造函数,会发生什么情况?

  • 调用 super() 方法(无参数化 Object 的 类构造函数)的类是否是抽象有关系吗?

    <
  • 最佳答案

    Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

    仅仅因为您拥有它,并不意味着它会被自动调用。您必须调用它,这就是对象实例化开始的地方。

    Why isn't the super() method called in the unparametrized constructor in the example above?

    这不是一种方法。它只是调用父类(super class)的默认构造函数。你知道吗,如果你没有调用它,Java 编译器会在给你字节码的同时自动插入该语句。因此,除非您想调用特定的构造函数,否则不需要在子构造函数中编写 super()

    What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

    别担心。如上所述,编译器会为您插入它。

    Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?

    是的,抽象与否并不重要。它只是调用父类(super class)构造函数。

    关于java - 调用对象的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098224/

    相关文章:

    c++ - 如何调用基类构造函数?

    java - 如何在 java 中为特定构造函数创建方法?

    c++ - 使用c++静态类成员控制所有类实例的 "mode"

    Java赋值

    java - 确定所有 Java 发行版中的主要 Java 版本

    java - jdk 9 中弃用的 jnlp 和 java web 启动技术 - 替代方案?

    java - Gson 反序列化 json。 java.lang.RuntimeException : Failed to invoke public com. derp.procedure.model.SkeletonElement() with no args] 根本原因

    java - 默认构造函数的隐式 super 构造函数 Num() 未定义。必须定义一个显式的构造函数,这背后的逻辑是什么

    java - 构造函数有很多元素。如何重构(工厂模式)

    java - 以编程方式触发 MouseMove java