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();
}
...
}
Posted at 01:15PM Mar 10, 2009
by lance in Java |
Comments[3]
Posted by Darryl W. on March 11, 2009 at 06:05 AM CDT #
int thingy = bar;
or
int thingy = getBar();
Posted by Lance on March 11, 2009 at 06:09 AM CDT #
[Posting w/html, to make it more readable.]
Is it best to reference Foo properties by name, or, is it preferred to use the getter?
Which is the best practice inside Bletch?
>Integer thingy = bar;
-or-
Inteter thingy = Foo.getBar();
-or-
Integer thingy = Bletch.getBar();
-or simply-
Integer thingy = getBar();
Where:
getBar() is only defined in
Foo, not, Bletch.
Posted by Darryl W. on March 11, 2009 at 06:21 AM CDT #