Unit 2: Lesson 10 (#2 D): Does not make sense

This is exercise #2, letter D. Could someone help me understand why this code works the way it does. Just having a hard time wrapping my brain around this one.

public boolean hasGreaterProfit(FoodTruck otherTruck) {

//this line of code is what I am having trouble understanding
if (addBonus(this) > addBonus(otherTruck)) {
  return true;
} 
else {
  return false;
} 

}

Hi Jeff,
I’m sorry you are having a hard time with this exercise!
I’m not sure if I am looking in the right spot to see this exercise-- Unit 2 lesson 11 is a project lesson for the store management project, and doesn’t have an exercise like this. But from what you have posted of this exercise, here is my take:

The hasGreaterProfit(FoodTruck otherTruck) is a method that will be called on one Food Truck, that then passes in a parameter that is a different FoodTruck. After the two different Food Trucks have been instantiated, let’s say they are called truck1 and truck2, the method call will look like:

truck1.hasGreaterProfit(truck2);

It looks like addBonus() is a method that takes a FoodTruck object in as a parameter, does a calculation, and returns a number for that FoodTruck. The condition in the if statement is checking how the addBonus method calculates that number for the two different FoodTrucks.
addBonus(this) is finding the number for the Food Truck that the hasGreaterProfit method is called ON- in my code example this refers to truck1.
addBonus(otherTruck) is finding the number for the Food Truck passed as a parameter to the method hasGreaterProfit - in my code example otherTruck is truck2.

The if condition then checks if this Food Truck’s addBonus (truck 1’s) is larger than the otherTruck’s addBonus (truck2’s). The method returns true if this, truck 1’s addBonus is bigger and false if it is not bigger.

I hope this helps you get how this code works, let. If you can, please reply with a link to the level this came from, so we can move move this post to that lesson level, and others can get a heads up about this tricky method.

Best,
Lindsay

Hi, @jeff.rhodes, I edited the title of this thread because it is Unit 2: Lesson 10. Wonderful question and I think that @lindsay.davis had a wonderfully in depth explanation to this tricky/ nuanced use of the keyword this. I have also included an image diagramming what Lindsay was explaining with truck1 and truck 2 in the context of the method:


Please don’t hesitate to reach out for further clarification.

-Sam