CSC152 2004F, Class 17: Inheritance Admin: * HW due. * A note on casting. * Suppose A and B are in different classes. Should the be equal if they have the same string representation? If so, use return this.toString().equals(other.toString()); * Good idea: More general, "March" might reasonably be the same as the thing created by new Month(3). * Bad idea: If something's in a different class, logic tells us that it's different, and therefore not equal. (Equality of name says nothing about actual equality.) * HW assigned. * Exam distributed (and discussed). * Ask questions in class. * Email me questions. * Visit me in the office to ask questions. * Call me at home if necessary (before 10 p.m.) * Grading still not complete. Apologies. Overview: * Code reuse * Inheritance: Reusing code from class to class * Inheritance in Java * Polymorphism * Single inheritance * A problem: Constructors * Example /Code Reuse/ * An important goal of software engineering: Programmers should not have to "reinvent the wheel". * If you have to solve a problem similar to one already solved, you should be able to use as much of the previous code as possible. * Most OO languages provides two forms of code reuse: * Polymorphism: If you write code that uses a "general" set of methods, it can work with anything that provides those methods. (A graduate student can test anything that provides the Vec2D methods; we can compute the square of anything that provides a multiplyBy method.) * Inheritance: Once we've built one class, we can build a new, similar, class that adds or replaces capabilities without copying code. /Inheritance in General/ * We tend to talk about inheritance in terms of the "is a" relationship. * Every fraction is a number. * Every circle is a drawable object. * Every library book is a book. * Every colored point is a point. * Terminology: The class on the left is a subclass, the class on the right is a superclass * Fraction is a subclass of Number * Point is a superclass of ColoredPoint * Language design decision: Can one class have more than one superclass? * Yes: Models reality well. * No: Can be confusing. What if both superclasses have a method with the same name but different meanings? * Java says "only one superclass" * Benefits of inheritance (the "is a" relationship). * The subclass automatically "inherits" all the fields of the superclass. * The subclass automatically "inherits" all the methods of the superclass * However, * The subclass may add new fields and methods. * The subclass can "override" existing methods, giving them different definitions. /Inheritance in Java/ * Write public class SUBCLASS extends SUPERCLASS { } * Forget about the homework assignment. Just work on the exam.