Download presentation
Presentation is loading. Please wait.
Published byBrianna Haynes Modified over 9 years ago
1
Lecture 26: 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 expanding & shrinking –mapping from a point in one 2D space to another Today review & new object oriented concepts
2
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
3
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”); } }
4
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
5
Lecture 26: Inheritance Example Inheritance Hierarchy and Instance Variables Motor Vehicle CarTruckMotorcycle HarleyHondaKawasaki miles per gallon max speed... tires passengers seat storage cup holder... colors standard features extras
6
Lecture 26: Inheritance Inheritance in Java... Object TransformationGraphRectangle 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
7
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.