For this question, there is a check-box beside each requirement that you must sa
ID: 3846502 • Letter: F
Question
For this question, there is a check-box beside each requirement that you must satisfy. You need to do (at least one of) the following: Demonstrate good encapsulation throughout your class The situation that you're going to model with your classes is a CargoShip (i.e., one of those giant, ocean-going boats that carries cargo around the world), and the Cars that get inside the CargoShip. Each CargoShip has a maximum weight that it can be loaded with, which is specified in the constructor. For example, if the maximum weight is 10,000, and each Car weighs 1,000 pounds, then the CargoShip will be able to fit 10 Cars inside Each CargoShip is also limited to having space for no more than 20 Cars, no matter what the weight total is The Car objects must be stored in an array inside the CargoShip Add any methods to the Car that you need to in order to get this to work You need to write up that will enable the following program to compile, to run, and produce the output listed after it. Methods that you need to implement are bold-faced and highlighted in the code, in order to make them easier to find.Explanation / Answer
import java.util.ArrayList;
import java.util.List;
public class CargoShip {
List<Car> list=new ArrayList<Car>();
private int maxWeight;
private int totalWeight=0;
final int MAX=20;
public int getMaxWeight() {
return maxWeight;
}
public void setMaxWeight(int maxWeight) {
this.maxWeight = maxWeight;
}
public CargoShip(int maxWeight) {
super();
this.maxWeight = maxWeight;
}
public boolean TryToAddCar(Car c){
boolean added=true;
if(list.size()<MAX&&totalWeight<maxWeight&&(totalWeight+c.getWeight())<=maxWeight){
list.add(c);
}
else{
added=false;
}
return added;
}
public void printAll(){
for(Car c:this.list){
System.out.println(" This car has a weight of :"+c.getWeight());
}
}
}
package sample1;
public class Car {
private int weight;
public Car(int weight) {
super();
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void Print(){
System.out.println("This car has weight of :"+this.weight);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.