CSC152 2005F, Class 37: Inheritance Admin: * Exam 2 ready. Due next Friday. * No additional homework for the next week. * Swing tonight at 9:30 in Harris this weekend. Extra credit! * Lessons tonight in South lounge at 5:30 for beginners, 6:30 for advanced. Extra credit! * Two more football games for extra credit, too. Overview: * Reuse * Inheritance * Inheritance in Java * Special issue: Constructors * Example * Inheritance and interfaces About the exam * Making change * Suppose in Samsville, the demoniations are 25, 10, and 1 *To find the fewest coins to make N cents (a) Find out how many coins to make N-25 cents, call that a (b) Find out how many coins to make N-10 cents, call that b (c) Find out how many coins to make N-1 cents, call that c * The fewest coins to make N cents is 1 + min(a,b,c) * In Foosburg, the denominations are 49, 18, 7, and 3 *To find the fewest coins to make N cents (a) Find out how many coins to make N-49 cents, call that a (b) Find out how many coins to make N-18 cents, call that b (c) Find out how many coins to make N-7 cents, call that c (d) Find out how many coins to make N-3 cents, call that d * The fewest coins to make N cents is 1 + min(a,b,c,d) Reuse * When we need to do something similar to what we've already done, it doesn't require lots of extra work * One strategy: Copy, paste, and modify * Problem: If the original code was wrong or slow, you need to remember to propagate any changes you make * Problem: Your programs are big and repetitious * We need more general ways to write things * Strategy one: Interfaces and polymophism * This strategy does not cover all the cases in which we have code resuse * Does not cover "I want to design an object similar to one I've designed before" * Inheritance permits you to define new classes in terms of old *without copying code* If class A inherits from class B * A automatically gets all the fields (not just static) of B * A automatically gets all the methods of B * A can add new methods * A can add new fields * A can *change* the methods of B * Polymorphism: A's can be used wherever B's are expected In Java, we write public class A extends B { }