Tuesday Mar 10, 2009

Tomacco

I had another programmer come over and ask me a question that centered around inheritance. Specifically, trying to understand how/why subclass Bletch could see property 'bar' from superclass Foo:

public class Foo {
   int bar;
   ...
}

public class Bletch extends Foo {
   public int count() {
      return bar++;
   }
   ...
}
I reminded him how inheritance works (he is new to OO), but we also discussed composition. As an example I worked up to the Tomacco plant: it extends Tomato, but contains an instance of Tobacco so that it can respond to hasNicotine():
public class Tomacco extends Tomato {
   Tobacco t = new Tobacco();

   public boolean hasNicotine() {
      return t.hasNicotine();
   }
   ...
}