经过一番研究,我发现当子类扩展父类时,super()
是有益的。
但是如果我有 1 个带有两种方法的 Foo.class
该怎么办
private variable variable;
private String variable2;
public Foo()
{
this.variable = new variable();
}
和
public Foo(String Paramater)
{
super();
this.variable2 = Paramater;
}
从使用 super()
时调用第一个方法的意义上来说,这是否有效
只是为了澄清我的问题..有人可以向我解释一下这段代码中发生了什么吗?
public ProductDimensions() { }
public ProductDimensions(String sku, String size, double width, double depth, double height, double weight) {
super();
this.sku = sku;
this.size = size;
this.width = width;
this.height = height;
this.depth = depth;
this.weight = weight;
}
当我的类没有扩展任何东西时,为什么会调用 super ?难道只是没用吗?
最佳答案
构造函数中的
super()
始终调用基类中匹配的构造函数。在这种情况下可能是java.lang.Object
。因此,在您的代码中,这两个构造函数除了位于同一个类中之外没有任何关系。
如果您想在同一个类中链接构造函数,则必须使用 this()
(或必要的参数)。
关于java - 从重载类方法调用 super() 是否使用非参数化方法中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312787/