Java构造函数使用此链接()

时间:2015-04-15 07:53:52

标签: java

如果在构造函数链接场景中,我想在子类构造函数中使用参数化super()来调用超类' this()之前的参数化构造函数然后如何编码? 因为在类子构造函数中super()之前没有提到this()而自动调用超类默认构造函数但是如果我想在super()中调用参数化构造函数给出参数那么如何?因为明确表示不允许在super()之前提及this()。 请回复,提前致谢。

class Parent {



Parent() {
        System.out.println("Welcome in Parent class'Default Constructor"); 
      } 
      Parent(int x) {
        System.out.println("Welcome in Parent class'Parameterized Constructor"); 
        System.out.println("Your Lucky no.is: "+x); 
      } 
    } 



    class Child extends Parent
    {
      {
        System.out.println("I am in init block.");
       }

    Child()
    { 
       // super(7); ERROR!!
      this(10);
      System.out.println("I am in constructor Child()");

    }

    Child(int x)
    { 
     this(20,30);
     System.out.println("I am in constructor Child(int x)");  


    }
    Child(int x,int y)
    {
     
     System.out.println("I am in constructor Child(int x, int y)");  

    }

    public static void main(String arg[])
    {
    System.out.println("I am in main");
    new Child();
    System.out.println("Again I am in main");

    }



    }

}




3 个答案:

答案 0 :(得分:3)

构造函数无论是隐式还是显式都不能同时使用super()this()调用。您可以链接到超类构造函数(super())或相同的类构造函数(使用this())。

所以,如果你想调用参数化的超类构造函数,那么就这样做而不提及this()调用。它会起作用。

答案 1 :(得分:1)

请尝试以下课程

public class test2 {
    public static void main(String a[]){
        test1 tst1 = new test1(1,2,3);

    }

public class test1 {
    int a;
    int b;
    int c;

    public static void main(String[] args) {

    }

    public test1(){
        System.out.println("am in default const");
    }

    public test1(int a){
        this();
        this.a=a;
        System.out.println("am in one param const");
    }

    public test1(int a,int b){
        this(a);
        this.b=b;
        System.out.println("am in two param const");
    }

    public test1(int a,int b,int c){
        this(a,b);
        this.c=c;
        System.out.println("am in three param const");
    }

答案 2 :(得分:0)

您可以从Child的构造函数中调用super()。 如果您不在子构造函数中提及super,那么在这种情况下,将使用 super()调用父级的默认构造函数。但是,如果要调用父级的参数化构造函数,则使用 super(传递与父级构造函数的签名匹配的参数)

请参阅以下代码:

class Parent {
  Parent() {
    this(30);
    System.out.println("Welcome in Parent class'Default Constructor"); 
  } 
  Parent(int x) {
    System.out.println("Welcome in Parent class'Parameterized Constructor"); 
    System.out.println("Your Lucky no.is: "+x); 
  } 
}


public class Child extends Parent{


  Child(){
    this(25);
  }

  Child(int x){
    super(x);
  }

  public static void main(String arg[]){
    Child child= new Child();

    Child child1= new Child(20);


  }
}

输出:

Welcome in Parent class'Parameterized Constructor
Your Lucky no.is: 25
Welcome in Parent class'Parameterized Constructor
Your Lucky no.is: 20

在父构造函数中,您将注意到从默认构造函数中调用参数化构造函数。这可以在 this(30)的帮助下实现。

编辑:您不能同时使用super()和this()。