Search code examples
javaarraysgetter-settersetterinstance-variables

Does the array instance variable not relate to the setter method intake?


In the main method I make a new object of the DotComClass and set locationOfShips array to 14 numbers. Then send those values as an argument over to the setter method (setLocations) in the other class (see below). My question is why does it allow that pass over without issue, since I set the max number of elements of the locations instance variable is 5?


  import java.util.Arrays;

  public class Main {
    public static void main(String[] args) {
      DotComClass dotCom = new DotComClass();
      int[] locationOfShips = {6,7,8,9,1,2,3,4,4,4,4,5,5,5};        
      dotCom.setLocations(locationOfShips);       
    }
  }

  public class DotComClass {
   int [] locations = new int[5]; // is this not related to the locations in the setter?

   public void setLocations (int[] locations){
     this.locations= locations;
     System.out.println(Arrays.toString(locations));
     }
  }

Solution

  • The locations field is a reference to an array.

    This points that reference to a new array of 5 integers.

    int [] locations = new int[5]; // is this not related to the locations in the setter?
    

    This re-points that reference to a different array.

    this.locations= locations;
    

    The new array has its own size. It's not limited by the size of the array that the reference formerly pointed to.