2017-07-24 99 views
2

我想了解Java构造函数super()。让我们来看看以下课程:了解Java超级()构造函数

class Point { 
    private int x, y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public Point() { 
     this(0, 0); 
    } 
} 

该课程将编译。如果我们创建一个新的Point对象说Point a = new Point();没有参数的构造函数将被调用:Point()

纠正我,如果我错了,在做this(0,0)之前,Class构造函数将被调用,只有Point(0,0)将被调用。 如果这是真的,说默认调用super()是否正确?

现在,让我们看看相同的代码与一个小的变化:现在

class Point { 

     private int x, y; 

     public Point(int x, int y) { 
      this.x = x; 
      this.y = y; 
     } 

     public Point() { 
      super(); // this is the change. 
      this(0, 0); 
     } 
    } 

,代码将无法编译,因为this(0,0)不在构造函数的第一线。这是我感到困惑的地方。为什么代码不能编译?无论如何都不会调用super()? (如上所述的类构造函数)。

+0

点不是子类。想象一下,如果我们有一个子类PrettyPoint,那么PrettyPoint(){super(0,0); }会从上面调用Point(int x,int y)。 – ZeldaZach

+1

这将帮助你理解:https://stackoverflow.com/questions/10381244/why-cant-this-and-super-both-be-used-together-in-a-constructor –

+0

@ZeldaZach一切都是一个子类'对象'。 –

回答

4

您还可以从同一个构造函数this()super()但不能同时使用。当您拨打this()时,super()会自动从其他构造函数(您使用this()调用的函数)中调用。

+0

因此,我有超级()的2个电话。谢谢。 – Romansko

+1

@Rom如果代码可以编译,那会是结果之一,是的。 –

1

通过调用this(...),您不得不在您要调用的构造函数中调用超级构造函数(如果存在)。

调用this(...)super(...)始终是您在构造函数中调用的第一个方法。

编辑

class Point { 
    private int x, y; 

    public Point(int x, int y) { 
     super(...); //would work here 
     this.x = x; 
     this.y = y; 
    } 

    public Point() { 
     this(0, 0); //but this(...) must be first in a constructor if you want to call another constructor 
    } 
} 
+0

这正是我的观点。如果我被迫调用超级构造函数,如果我通过super()显式调用它,然后调用这个(..),会有什么不同? – Romansko

+1

作为第二种方法,您不能打电话给super/this。如果你想调用一个超级构造函数,你需要在你调用的构造函数中完成。 – Cedric

5

this(0, 0);将调用,同一个类的构造函数和super()会调用Point类的超/父类。

现在,代码将不会编译,因为此(0,0)不在构造函数的第一行 中。这是我感到困惑的地方。为什么代码不会 编译?不是super()被调用吗?

super()必须构造的第一行,并且还this()必须在构造函数中的第一行。所以两者都不能在第一行(不可能),也就是说,我们不能在构造函数中添加两者。

作为一个关于你的代码explonation:

this(0, 0);将调用采用两个参数(在Point类)的构造函数和两个参数的构造函数会调用到super()隐式(因为你没有明确地称呼它)。

4

把超级()放在你的第一个构造函数中,它应该工作。

class Point { 
 

 
     private int x, y; 
 

 
     public Point(int x, int y) { 
 
      super(); // this is the change. 
 
      this.x = x; 
 
      this.y = y; 
 
     } 
 

 
     public Point() { 
 
      
 
      this(0, 0); 
 
     } 
 
    }

1

构造函数可以使用方法调用super()来调用超类的构造函数。只有约束是它应该是第一个陈述。

public Animal() { 
    super(); 
    this.name = "Default Name"; 
} 

这段代码会编译吗?

public Animal() { 
    this.name = "Default Name"; 
    super(); 
} 

答案是NO 。应始终在构造函数的第一行调用super()