0

I am having problems with a current assignment I got (done in Java). I have been given a project to do with an abstract class and subclasses. However, I am stuck with creating the copy constructor for it because I keep getting the error: actual and formal argument lists differ in length. Here, arr is the abstract "super" class with the constructor function inside it only being defined (shown below). The constructor has arguments that correspond to the rows (m) and columns (n) of the 2D array. In the Board class (which extends arr), I have to define both the constructor and copy constructor. I have defined the constructor using super(m,n) but I cannot define the copy constructor (and I am not sure of the subclass constructor is correct here too).

In the arr class:

protected int a, b;
protected Arr (int height, int width) { 
   a = height; 
   b = width; 
}

In the board Subclass:

public class Board extends Arr{
private int[][] space;
public Board (int a, int b){
   super(a,b);
   this.space = new int[a][b];
}

The Copy Constructor

public Board(Board X) {
   board copy = new Board(a,b);
   copy.space = X.space;
}

I get an error on the line "public board(board X) {" as it seems that I have the wrong arguments. However, I am not allowed to change the arguments here. From my previous research about this, I only know that the copy constructor copies the argument object, but I cannot do that because I do not how to make one. Thanks for your help

  • You should follow the Java Naming Conventions. As @Michael already said, class names are written in PascalCase (i.e. `board` should be `Board`), method and variable names are written in camelCase (i.e. `X` should be `x`). – MC Emperor Apr 11 '19 at 10:33

1 Answers1

1

You are missing the keyword "class" from the class definition, for a start:

public class board extends arr

Your copy constructor is incorrect:

board copy = new board(a,b);
copy.data = X.data;

All you are doing is creating a different board instance which immediately gets thrown away. You are not setting any values of this instance.

You need to call the super constructor:

super(X.m, X.n);

Class names should be PascalCase

Michael
  • 41,989
  • 11
  • 82
  • 128
  • Thank you!!!! That has sorted out the problem. I didn't understand why but now I do, thank you. Also I copied down some of the code wrong so that's why I missed out on the class keyword. Thank you for your help! – CanOfTomatoes Apr 11 '19 at 10:26
  • Once I call "super(X.m, X.n);" do I have to write any follow up? Like "this.space = space?" – CanOfTomatoes Apr 11 '19 at 10:34
  • Yes, you need to copy `space` separately but you probably want to do a [deep array copy](https://stackoverflow.com/questions/5617016/how-do-i-copy-a-2-dimensional-array-in-java/13792183) rather than simply assigning it. – Michael Apr 11 '19 at 10:42