Index

Step-By-Step


For try #1, we'll code without using interfaces.

Elephant1
  • A minimal model of a lovely elephant
  • For brevity, it just has one ivar
#1
public class Elephant1 {
#2
private int weight; public Elephant1(int aWeight) { this.weight = aWeight; } public int getWeight() { return weight; } }
PopcornMachine1
  • A minimal model of a popcorn machine
  • For brevity, it just has one ivar
#1
public class PopcornMachine1 {
#2
private int weight; public PopcornMachine1(int aWeight) { this.weight = aWeight; } public int getWeight() { return weight; } }
Zoo1
Our zoo class.

  • Class header
  • List of objects at the zoo (elephants, desks, popcorn machines and many more types)
#1
public class Zoo1 { private String name;
#2
private List<Object> objects;
Zoo1 Method 'getTotalWeight'
Our main software requirement is to compute the total weight of our objects. So we've coded a method "getTotalWeight".

Oops, a compiler error! 😕 Type "Object" does not understand message "getWeight".
public int getTotalWeight()  {
	int totalWeight = 0;
	for (Object eachObject: this.objects)
		totalWeight += eachObject.getWeight();
	return totalWeight;
}

Completed Code


Here are the completed classes:

Conclusion


  • Zoo is sending our specialized message "getWeight"
  • The receiver of the message is type "Object"

Type "Object" is very general and does not understand "getWeight" (in fact, it only knows a few general methods like "toString" and "equals") 😕

We need a specialized type that understands "getWeight" 👍🏽

Are you ready for Try 2?