Using inheritance hierarchies By CW Hanley 322015 Understanding
Using inheritance hierarchies By CW Hanley 3/2/2015
Understanding base classes • Base classes are higher up on the hierarchy • They are many times abstract, which means you cannot make an instance of them • They exist to hold common elements and to be extended • If they are abstract, they need at least one abstract method • Abstract methods have no definitions and must be overridden eventually
How to write child classes 1. Make sure you extend the parent 2. Make sure you pass information up to parent constructor via super(var 1, var 2); This MUST be the first line in the constructor!!! 3. Over-ride the appropriate method with your logic 4. From your client program, make either an array or Array. List of the base class 5. After instantiating your objects, use a for loop to call the polymorphic method 6. Java will find the appropriate logic depending upon the type of object it finds 7. You can use the instanceof command in java to figure out what type of object you are dealing with
Classic inheritance hierarchies • What are some classic inheritance hierarchies? • • Employee and Payroll Shape and Painting Entities in a world acting Decks of Cards for various games Boards for various games GUI components Library Loan Item Consumer Items to be purchased
When is it OK to make a new object of a certain type? • In general, if you can read “is a” from right to left, it is OK to create an instance of a certain class. • Try Sample Problems • You “cast down the hierarchy” • In general, you cast from a higher level on the hierarchy down to the lower level • instanceof • This command returns true if the object on the left is an instance of the class on the right or if it implements the class on the right
- Slides: 5