user828835
user828835

Reputation: 57

Initializing array on the fly in constructor (Java)

 public class A{
      public A(int[] a){}
 }

 public class B extends A{
      public B(double[] b){
           super({b.length});  //ERROR
      }
 }

I want to be able to compile the code above. To clarify, I have class A and B that extends it. Class A does not have an empty parameter constructor. If I don't put a call to super in Class B's constructor on the first line, it will try to call super(), which doesn't exist. But, I want to call super(int[] a) instead. I want to do this by taking the length of a given double array and sending it as an array with length 1. It does not let me do this because apparently you can't declare an array like that, and if I were to declare it on a separate line it would call super() first and that won't work.

Is there any way to declare an int[] on the fly like that? Or are the only solution here to either make a constructor for A with no parameters or make my own function that returns an int[]?

(Don't ask why I want to send it as an array like that.)

Upvotes: 5

Views: 15972

Answers (3)

corsiKa
corsiKa

Reputation: 82559

If you insist on not asking why...

You could make the array, assign the first and only element and send it.

public class B extends A{
      public B(double[] b){
           int[] arr = new int[1];
           arr[0] = b.length;
           super(arr);  // broken, super must be first.
      }
}

This means you must have a one line solution. Luckily, Java provides an in-line way to make a series of elements into an array at compile time.

public class B extends A{
      public B(double[] b){
           super(new int[]{b.length});  // FIXED
      }
}

Upvotes: 11

OscarRyz
OscarRyz

Reputation: 199195

Yeap, try:

 super(new int[]{b.length});  //ERROR NO MORE

Upvotes: 4

irreputable
irreputable

Reputation: 45433

you can also

 public class A{
    public A(int... a){}
 }

 public class B extends A{
    public B(double[] b){
       super( b.length ); 
  }
 }

Upvotes: 4

Related Questions