lecture 26: inheritance announcements & review lab 8 due thursday image and color effects with...
TRANSCRIPT
Lecture 26: Inheritance
Announcements & Review
Lab 8 Due Thursday
Image and color effects with 2D arrays
Last TimeImages as 2D arrays• color representation
– red, green, blue values– integer values
• expanding & shrinking– mapping from a point in
one 2D space to another
Today• review & new object
oriented concepts
Lecture 26: Inheritance
Object OrientedObject Centered View
• Objects with attributes and behaviors– attributes: instance variables– behaviors: methods
• Designing a Class– use private for encapsulation
• scopes the instance variables to the class methods
• no one else can directly modify them
– public methods for behaviors• local variables “disappear” after the method
returns
– use private helper methods when necessary
Lecture 26: Inheritance
Example Local vs Instance Variable
public class Rectangle { private int width; // the instance variables private int height; public Rectangle() { width = 0; height = 0; } public Rectangle(int w, int h) { width = w; height = h; }
public int getArea() { int area = width * height; // area is local variable // Aside: int width = ... BAD PRACTICE, never name a
local // variable the same name as an instance variable if (area > 0) { return area; } else {
System.out.println (“Bad Rectangle”); } }
Lecture 26: Inheritance
Why Inheritance?
• Reuse in common functionality in related classes
• Reduce redundancy, ease programmer effort• Classification lets humans deal with
complexity, inheritance is a form of classification
• General to specific, e.g., cat to siameseRead:
– Chapter 9 Cahoon & Davidson– Chapter 9 Regis & Stepp
Additional Reading:http://java.sun.com/docs/books/tutorial/java/concepts/
inheritance.html
Lecture 26: Inheritance
Example Inheritance Hierarchy and Instance
Variables
Motor Vehicle
Car Truck Motorcycle
Harley Honda Kawasaki
miles per gallonmax speed...tires passengers
seat storagecup holder...
colorsstandard featuresextras
Lecture 26: Inheritance
Inheritance in Java ...
Object
Transformation Graph Rectangle
ColoredRectangle
Object provides these methods: toString() equals() // more on these clone() // later... instanceof()
All classes inherit from Object•Rectangle inherits from Object•ColoredRectangle inherits from Rectangle
Lecture 26: Inheritance
Syntax of InheritanceExample:
ColoredRectanglepublic class ColoredRectangle extends Rectangle { private Color myColor; // additional instance variables
public ColoredRectangle() { super(); // optional myColor = Color.white; } // Is the same as: public ColoredRectangle() { // implicitly first calls super,
because // the signatures match myColor = Color.white; } public ColoredRectangle(int w, int h, Color newColor) { super(w,h); // required: why do we need this one? myColor = newColor; }
Also, we have to change Rectangle’s instance variables to protected