请让我知道如何在Java的构造函数中将值作为3级传递吗?

时间:2019-02-18 06:41:27

标签: java constructor

这是我的主要功能。

class first{
  public static void main(String ar[]){
    second sc = new second();
  }
}

class second{
  second(third th){
    this.th = th;
  }
}


class third{
  private int i;
  third(int i){
    this.i = i;
  }
}

请告诉我解决方案而不更改构造函数参数。我不知道如何传递构造函数以及如何将构造函数的参数作为类的对象给出。

3 个答案:

答案 0 :(得分:1)

在自变量中调用second的构造函数(或首先创建一个变量并将其传递)

second sec = new second(new third(12));

答案 1 :(得分:0)

second构造函数需要一个third类的实例:

third th = new third(10);
second sc = new second(th);

答案 2 :(得分:0)

class first{
  public static void main(String ar[]){
    third third= new third(1);// make third type variable and pass this
    second sc = new second(third);
  }
}

class second{
  private third th; // Need to define this
  second(third th){
    this.th = th;
  }
}


class third{
  private int i;
  third(int i){
    this.i = i;
  }
}