Classes and Inheritance

Download Report

Transcript Classes and Inheritance

Announcements & Review
Lab 8 Due Thursday
Image and color
effects with 2D
arrays
Last Time
Images as 2D arrays
•
•
color representation
–
–
red, green, blue values
integer values
–
mapping from a point in
one 2D space to another
expanding & shrinking
Today
•
review & new object
oriented concepts
Lecture 26: Inheritance
Object Oriented
Object 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 siamese
Read:
– 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
miles per gallon
max speed...
tires
passengers
Motor Vehicle
cup holder
...
Car
colors
standard features
extras
Truck
Harley
Motorcycle
Honda
Lecture 26: Inheritance
seat storage
Kawasaki
Inheritance in Java ...
All classes inherit from Object
•Rectangle inherits from Object
•ColoredRectangle inherits from
Rectangle
Object provides these methods:
toString()
Object
equals()
// more on these
clone()
// later...
instanceof()
Transformation
Graph
Rectangle
ColoredRectangle
Lecture 26: Inheritance
Syntax of Inheritance
Example: ColoredRectangle
public 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
Lecture 26: Inheritance