As many other programmers in this thread have stated, if you're using inheritance to achieve code-reuse, in such a fashion that you're not creating a relationship, but rather just saving yourself typing and work, then you're probably doing it wrong -- but that's from a software engineers perspective.
If you're using inheritance to create a "is a" relationship, then you're doing it the right way, for example:
public abstract class Human {
private int itsAge = 0;
private int itsWeight = 0;
public Human(int itsAge, int itsWeight) {
setItsAge(itsAge);
setItsWeight(itsWeight);
}
public setItsAge(int itsAge) {
this.itsAge = itsAge;
}
public setItsWeight(int itsWeight) {
this.itsWeight = itsWeight);
}
}
public class Woman extends Human {
public boolean isBeautiful = True;
public Woman() { super(25, 125); }
}
If you're using inheritance to create a "has a" relationship, then you're talking about composition, for example:
// Continuation of the code above.
public class Woman extends Human {
public boolean isBeautiful = True;
public NiceRack niceRack = new NiceRack(34D);
//... bla bla bla
}
In this case, you can see composition, because you can say that the Woman class, "has a" NiceRack.
If you're using inheritance to code to a contract and enforce a kind of behavior, then you're talking about using interfaces. (I love interfaces).
public interface ISexyTimeable {
boolean sexyTime(ISexyTimeable someoneElse);
}
public class Woman extends Human implements ISexyTimeable {
public boolean isBeautiful = True;
public NiceRack niceRack = new NiceRack("34D");
//... bla bla bla
public boolean sexyTime(ISexyTimeable someoneElse) {
return true;
// This implementation is arbitrary, all we can go on
// is that, according to the interface ISexyTimeable,
// this class, in order to implement the interface,
// must have a sexyTime() method that takes another
// ISexyTimeable object as a parameter and returns a
// boolean.
// In this case, sexyTime will always return true;
}
}
On the other hand, doing the following is a really bad idea:
public class someSetOfUtilityMethods {
private someSetOfUtilityMethods() {}
public void someLongUtilityMethodThatDoesALotOfStuffIDontWantToType() {
}
}
public class A extends someSetOfUtilityMethods {
public void b() {
super.someLong....IDontWantToType();
}
}
Get it?
In my opinion, learning to use Utility classes is a great way to learn about encapsulation. I make it a habit, in each of my projects, to create a blank static class file (that I usually have set as a class library) to store utility methods in. And I call them from around the project.
(I know this is probably going to get deleted, but I wanted the poster to see it before it was, just because, sexual innuendos are so much easier to remember.)