- 当类已经有参数化构造函数和非参数化构造函数时,为什么类应该调用 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/