5
 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.)

3 Answers 3

11

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
      }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I did not know you can declare and initialize arrays like that at the same time. That is just what I was looking for.
HOWEVER, your first solution would still not work because you're missing a call to super() in the first line of the constructor, so it would be called automatically. But since I lack a constructor A(), this would cause an error. Thanks anyway, though.
The first example won't compile. You need to call super/this constructor at the very first line. Second exp +1.
You can't call super like that in your first code. The correct answer is the second one
4

you can also

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

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

Comments

4

Yeap, try:

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

1 Comment

No, that would just make the length of the array equal to b.length. I want the length to be 1, and the value of the first (and only) entry to be b.length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.