inheritance chapter 10 programs built from objects/instances of classes an o.o. approach – build...
TRANSCRIPT
InheritanceChapter 10
Programs built from objects/instances of classes
An O.O. approach – build on earlier work. Use classes in library and ones you have
written before
Using a class similar to one already written in text “Sphere” page 193
• Sphere has radius and position (actually draws an Oval.)
• protected will be used for inheritance
• Class “Bubble” page 194 will “extend” Sphere. Bubble inherits from Sphere.
• Bubble is a sub class of Sphere
• “protected” less private than private– More private than public
private int x, y;
• // x and y can not be used by another class
• protected int x , y; // can be used by another subclass
Scope rules: access
• public – from anywhere
• protected – from the class and sub classes
• private – only from the current class– local variables only inside a particular method
Overriding/Overloading
• Overriding: same name and parameters
• Overloading: method with same name as class but different parameters
• Subclass may add additional methods, variables and override methods of it’s parent
Class Diagrams: show which classes inherit from others
Object
Bubble Ball
A sub class
Java uses single line inheritance
Any public or protected method may be used by any sub class if the child “extrended” the parent class
“super” – used by subclass to call it’s immediate superclass
super.display(paper); // uses super class method “display” and not the method in the child class (sub class) “display”
constructors
• Use “new”• A class with no constructors – Java assumes a
single one with zero parameters• A class with one or more constructors that
require zero parameter constructor must be explicitly written. (Java does not assume it)
• Constuctors not inherited – must be explicitly called by sub class.
“Balloon” class page 199
• Holds a constructor “Balloon” which is passed through parameters
• “DifferentBalloon” page 200 – holds a constructor passed in two parameters– super( ) is called from the immediate super
class.
• “ModifiedBalloon” – holds a constructor, passed three parameters– Super is called with three parameters
final:
• Methods: declared final can not be overridden
• Variables: declared final can not be changed
• Classes: declared final can not be sub classed
Abstract classes
• A program that maintains graphical shapes – they are similar (position, color, size)
• Super class “Shape”
• Page 202– public abstract class Shape { …– public class Circle extends Shape { …
• paper.drawOval ( x, y, size, size);
Shape is incomplete
• The keyword ‘abstract’ used in Shape prevents attempts to create an instance of the class Shape
• display method in Shape is just a header the subclass must implement it as ‘display’ in Circle does.
• Any class that includes methods that are abstract must also be abstract
• Abstract classes higher up the class hierarchy become more general or abstract