Home > Enterprise >  How to set an array as a parameter for a constructor?
How to set an array as a parameter for a constructor?

Time:12-11

I'm doing an assignment for my class and this is my code.

public class Realty1 {
    Realty1 realty = new Realty1(incomeandCost[]);

    Realty1[] incomeAndCost = {
        new Realty1( 10000,  25000), new Realty1(35000,  100000), 
        new Realty1( 67000, 125000), new Realty1(89000,  199000), 
        new Realty1(105000, 250000), new Realty1(51000, 1025000)
    };
}

I'm just confused and not really sure how to accomplish this. I added the array as a parameter, because without it there the code doesn't work, but now I'm getting a ".class expected" error.

CodePudding user response:

It seems that actually two classes are needed here:

  • With two integer fields, constructed as Realty(int x, int y)
  • With Realty[] array field, constructed as Realty1(Realty[] arr)

Example:

public class Realty {
    private int x, y;

    public Realty(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Realty1 {
    private Realty[] incomeAndCost;

    public Realty1(Realty[] incomeAndCost) {
        this.incomeAndCost = incomeAndCost; 
    }

    public Realty1() { // default no-args constructor
        this(new Realty[] {
            new Realty( 10_000,  25_000), new Realty(35_000,  100_000), 
            new Realty( 67_000, 125_000), new Realty(89_000,  199_000), 
            new Realty(105_000, 250_000), new Realty(51_000, 1025_000)
        });
    }
}

CodePudding user response:

public class Realty1 {
  int A;
  int B;
  Realty1 realty = new Realty1(incomeandCost[]);
  public Realty1(int A, int B){
     this.A = A;
     this.B = B;
  }
  Realty1[] incomeAndCost = {
     new Realty1( 10000,  25000), new Realty1(35000,  100000), 
     new Realty1( 67000, 125000), new Realty1(89000,  199000), 
     new Realty1(105000, 250000), new Realty1(51000, 1025000)
  };
}
  • Related