Friday, August 10, 2012

Inheritance and Java Basics

These are some notes from a java/c class I took 


Why or why not use inheritance?

  • When programs get large, it's easier to use object oriented programming, because it's easy to understand things in terms of objects.
  • Don't need to use inheritance.
  • It's good for software reusability.
  • Be careful not to use "is a" relationships where it sounds ok, but programmitically it doesn't work, like with a square is a rectangle.
  • This relationship is true, however, there can be constraints for the rectangle that are different from a square, like different width and height maximums
  • problems if switching roles (same object playing 2 or more different roles at same time or at different times); don't use inheritance in this case, use composition
Containment (composition) instead of inheritance

  • Instead of extending (subclassing) parent class, you could create a separate class that declares a parent object for it's needs.
  • This means that each of these separate class objects have an extra parent class object.
  • The problem with this is that you may need to write the same functions declared in the parent class.
  • The software reusability of the parent class isn't taken advantage of.
  • Delegation is a consequence of composition (your extra object is called for work)
  • With composition you can't do this: point -> colored point, which is a big limitation (like editing all points by moving them)
Point [] P;
for (int i = 0; i <p.length; i++){
  p[i].moveright(2); //can't do this w/ containment
}


//colored point has point
Point [] p; //only hold pt
ColoredPoint [] cp; //can only hold colored point; need two different loops- one that looks like above and...

for (int i=0; i<cp.length;i++){
  cp[i].moveright(2);
}

No comments:

Post a Comment