从重载的类方法调用super()是否使用非参数化方法中的变量?

时间:2019-01-22 16:42:22

标签: java

经过一些研究,我发现当子类扩展父类时,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?只是没用吗?

2 个答案:

答案 0 :(得分:3)

构造函数中的

super()总是在基类中调用匹配的构造函数。在这种情况下,可能是java.lang.Object。因此,在您的代码中,这两个构造函数没有关系,只是它们在同一类中。

如果要在同一类中链接构造函数,则必须使用this()(或必要的参数)。

答案 1 :(得分:2)

super()用于传递带有匹配参数的父类的构造函数的参数。 即使您不放一个,编译器也会将其添加到构造函数的第一行。

在构造函数链接的情况下,即使用this()-匹配参数从另一个构造函数调用另一个构造函数。

在这种情况下,至少一个构造函数必须调用super()。

构造函数链接示例:

//Execute multiple constructors in chain
//Advantage: Allocation of multiple type of resources at initialization level. One constructor per resource example: GUI, Database, Network etc.
//Easy Debugging
//We use this() for constructor chaining.
//Can be achieved in any order.
class ConstructorChaining
{
ConstructorChaining()
{
this(10);//always the first line
System.out.println("Default Constructor Completed");
}
ConstructorChaining(int x)
{
this(x,20);//always the first line
System.out.println("X="+x);
System.out.println("Parameter 1 Constructor Completed");
}
ConstructorChaining(int x, int y)
{
// atleast one constructor without this() must be used. - here either you can write super() or compiler will add it for you.
System.out.println("X+Y="+(x+y));
System.out.println("Parameter 2 Constructor Completed");
}
public static void main(String... s)
{
new ConstructorChaining();
}
}
相关问题