Part I: Add a toString method to your Item class. This method does not accept an
ID: 3601183 • Letter: P
Question
Part I:
Add a toString method to your Item class. This method does not accept any parameters and returns a String reflecting the current state of the object. Once you have written the toString method, the following statement will display the contents of all member variables in an Item object called chair:
System.out.println(chair);
Part II:
Create an array of Item objects. Then write a loop that calculates the total weight of the Items in the array. Since the weight is a private data member of the Item class, the loop will need to call an accessor method to query the weight of each Item in the array.
Explanation / Answer
Here is the code :
import java.util.LinkedList;
class Item {
private String name;
private int weight;
Item(String name , int weight){
this.weight = weight;
this.name = name;
}
//PART 2 : getter function for weight
public int getWeight(){
return weight;
}
//PART 1 : To string method returns a string that displays all the member variable values
public String toString(){
String s = "Name : "+name+",Weight : "+weight;
return s;
}
}
public class Test {
public static void main(String[] args) {
Item chair = new Item("chair",123);
//PART 1 : This will call toString method and print the returned value
System.out.println("PART 1 : ");
System.out.println(chair);
//PART 2 : Create item array and print sum of weights using getter function
System.out.println("PART 2 : ");
//Create array of items
Item[] itemArray = new Item[4];
itemArray[0] = new Item("chair",10);
itemArray[1] = new Item("chair",12);
itemArray[2] = new Item("chair",32);
itemArray[3] = new Item("chair",44);
//Loop over array and calculate total weight using getter function
int totalWeight = 0;
for(int i = 0;i<itemArray.length;i++){
totalWeight+=itemArray[i].getWeight();
}
//Print total weight
System.out.println("Total Weight is : "+totalWeight);
}
}
Output :
PART 1 :
Name : chair,Weight : 123
PART 2 :
Total Weight is : 98
**If you have any query , please feel free to comment with details.
**Happy learning :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.