Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an object class with just one instance variable, an integer array. Your co

ID: 3929656 • Letter: W

Question

Write an object class with just one instance variable, an integer array. Your constructor should take an integer array as its only parameter. Write all the accessors, mutators, toString and equals methods. Also write an additional RECURSIVE method that returns the sum of all the elements in the array (your method should have an array as it's argument and should have the recursive call in its return for the general case). Write a client class to test all your methods and especially your recursive method.

Explanation / Answer


import java.util.Arrays;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

public class ArrayObject {
  
private int[] arr;
  
public ArrayObject(int[] arr)
{
this.arr = arr;
}
  
public int[] getArray()
{
return this.arr;
}
  
public void setArray(int[] arr)
{
this.arr = arr;
}
  
@Override
public String toString()
{
return Arrays.toString(this.arr);
}
  
public int sum(int[] arr,int index)
{
if(index == arr.length)
return 0;
else
return arr[index]+sum(arr,index+1);
}
  
public boolean equals(Object second) {
if (second == this)
return true;
  
if (second == null)
return false;
  
if (getClass() != second.getClass())
return false;
  
ArrayObject second_obj = (ArrayObject)second;
  
if(this.arr.length!=second_obj.arr.length)
return false;
else
{
for(int i=0;i<this.arr.length;i++)
if(this.arr[i] != second_obj.arr[i])
return false;
}
  
return true;
  
}
  
}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/


public class TestArrayObject {
  
public static void main(String[] args)
{
int[] arr = {1,2,3,4,5,6,7,8,9,10};
ArrayObject arrObj = new ArrayObject(arr);
System.out.println(arrObj);
  
int sumOfArray = arrObj.sum(arrObj.getArray(), 0);
System.out.println("Sum is : "+sumOfArray);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote