Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy, Andover, MA

Slides:



Advertisements
Similar presentations
Inheritance Inheritance Reserved word protected Reserved word super
Advertisements

1 CS1001 Lecture Overview Homework 3 Homework 3 Project/Paper Project/Paper Object Oriented Design Object Oriented Design.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 27 - Java Object-Oriented Programming Outline.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 CS1001 Lecture Overview Object Oriented Design Object Oriented Design.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
2.5 OOP Principles Part 1 academy.zariba.com 1. Lecture Content 1.Fundamental Principles of OOP 2.Inheritance 3.Abstraction 4.Encapsulation 2.
Abstraction, Inheritance, and Polymorphism in Java.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance using Java
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Programming Examples: C++, Java Advantages: 1. reusibility of code 2. ability to adapt (extend) previously written code.
Inheritance A Review of Objects, Classes, and Subclasses.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Object Oriented Programming
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
AD Lecture #1 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism.
AP Computer Science A – Healdsburg High School 1 Unit 2 - Object-Oriented Programming - Example.
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
OOP Basics Classes & Methods (c) IDMS/SQL News
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Software Construction Lab 05 Abstraction, Inheritance, and Polymorphism in Java.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Sections Inheritance and Abstract Classes
Object-Oriented Programming Concepts
Inheritance ITI1121 Nour El Kadri.
Lecture 12 Inheritance.
Inheritance and Polymorphism
03/10/14 Inheritance-2.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object-Oriented Programming
Chapter 5 Classes.
Presentation transcript:

Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy, Andover, MA

Why is The College Board using Java? Three reasons: OOP Java:

The Recommendations of the AP Computer Science Ad Hoc Committee : “Object Orientation involving encapsulation, inheritance, polymorphism, and abstraction, is an important approach in programming and program design. It is widely accepted and used in industry and is growing in popularity in the first and second college-level programming courses.”

Some other reasons to move on to Java: Internet applets Platform-independent software Relatively easy graphics and GUI programming Lots of library packages Free compiler and IDEs Colleges are teaching it Companies are using it Students want it (Teachers welcome it... ;) (Programmers drink it... :)

What are OOP’s claims to fame? Better suited for team development Facilitates utilizing and creating reusable software components Easier GUI programming Easier program maintenance

OOP in a Nutshell: A program models a world of interacting objects Objects create other objects and “send messages” to each other (in Java, call each other’s methods) Each object belongs to a class; a class defines properties of its objects A class implements an ADT; the data type of an object is its class Programmers write classes (and reuse existing classes)

Java != C++ class MyMath { public static long factorial(int n) { long f = 1; int i; for (i = 2; i <= n; i++) f *= i; return f; } public static void main(String[] args) { System.out.println("10! = " + factorial(10)); } It may be tempting to teach only conventional (procedural) programming in Java It would mean to miss the point

OOP

Case Study: Dance Studio

Exercise 1: Run the Dance Studio applet.

Exercise 2: Set up a project in an IDE (e.g. BlueJ) for the Dance Studio applet. Compile and run.

Quiz: How many classes were written for this applet? A. 1 B. 2 C. 5 D. 10 E. 17

Good news: The classes are fairly short In OOP, the number of classes is not considered a problem

How many Java/Swing library classes are used, explicitly or implicitly, in this applet? A. 4 B. 8 C. 12 D E Quiz:

Answer: E (hundreds)

/* 00/03/14 * Copyright Sun Microsystems, Inc. * All Rights Reserved. *... */ package javax.swing; import java.util.EventListener; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.plaf.*; import javax.swing.event.*; import javax.accessibility.*; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException;...

Abstraction... relevant to the given project (with an eye to future reuse in similar projects). Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the relevant ones... “Relevant” to what?

Abstraction

public abstract class Dancer { // Fields (data members): protected Foot leftFoot; protected Foot rightFoot; private String mySteps[]; private int stepIndex = -1; public void setSteps(String steps[]) { mySteps = steps; stepIndex= -1; } Continued 

Dancer (cont’d...) // Methods (member functions): public void nextStep() {... } public void makeStep(String sideStr, String weightStr, String dirStr) // e.g. makeStep("left", "weightboth", "F"); {... } public void draw(Graphics g) { leftFoot.draw(g); rightFoot.draw(g); } Continued 

Dancer (cont’d...) // Private Methods // (callable only from constructors and methods // of this class, i.e. "private" to the programmer // who wrote this class) private String[] parseNextStep() {... }

How is Dancer used in Dance Studio? public class DanceModel {... private Dancer dancers[]; public DanceModel(DanceFloor floor, int floorDir, String steps1[], String[] steps2) {... dancers = new Dancer[2]; dancers[0] = new MaleDancer(x1, y1, dir1); dancers[0].setSteps(steps1); dancers[1] = new FemaleDancer(x2, y2, dir2); dancers[1].setSteps(steps2);... } Continued 

DanceModel (cont’d...) public void nextBeat() { for (int k = 0; k < dancers.length; k++) dancers[k].nextStep();... }

Exercise 3: In the Dance Studio applet, change the DanceModel class to place four dancers (two couples) on the dance floor, as shown:

Hint: In DanceModel, add a MaleDancer and a FemaleDancer as follows: x y Dancer’s position (in pixels) dancer[...] = new MaleDancer(x, y, dir); Dancer’s orientation

Exercise 4: (a)Compile and run the Banner applet (b)Modify Walker.java so that instead of a flying banner, a “man” or a “woman” walks across.

Hint: Use MaleDancer or FemaleDancer — they can “walk” too... MaleDancer walker = new MaleDancer(x, y, dir); Make him/her take one step with one foot, then two steps with the other foot, etc. To make a step: walker.makeStep(side, "weightboth", "F"); "left" or "right"

Encapsulation Encapsulation means that all data members (fields) of a class are declared private. Some methods may be private, too. The class interacts with other classes (called the clients of this class) only through the class’s constructors and public methods. Constructors and public methods of a class serve as the interface to class’s clients.

Encapsulation

public abstract class Foot { private static final int footWidth = 24; private boolean amLeft; private int myX, myY; private int myDir; private boolean myWeight; // Constructor: protected Foot(String side, int x, int y, int dir) { amLeft = side.equals("left"); myX = x; myY = y; myDir = dir; myWeight = true; } Continued  All fields are private

Foot (cont’d...) // Public methods -- accessors: public static int getWidth() { return footWidth; } public boolean isLeft() { return amLeft; } Continued 

Foot (cont’d...) public int getX() { return myX; } public int getY() { return myY; } public int getDir() { return myDir; } public boolean hasWeight() { return myWeight; } Continued 

Foot (cont’d...) // Public methods -- modifiers: public void setWeight(boolean weight) { myWeight = weight; } public void move(int dx, int dy) {... } public void turn(int dir) { // dir > 0 -- clockwise; dir < 0 -- counterclockwise myDir = (8 + myDir + dir) % 8; } Continued 

Foot (cont’d...) // Public methods -- drawing: public void draw(Graphics g) {... if (isLeft()) drawLeft(g); else drawRight(g);... } // Public methods -- abstract: public abstract void drawLeft(Graphics g); public abstract void drawRight(Graphics g); }

Encapsulation ensures that structural changes remain local Changes in the code create software maintenance problems Usually, the structure of a class (as defined by its fields) changes more often than the class’s constructors and methods Encapsulation ensures that when fields change, no changes are needed in other classes (a principle known as “locality”)

Encapsulation (cont’d) Example: Suppose in Foot we decided to use private String mySide; instead of private boolean amLeft;

Before: public abstract class Foot {... private boolean amleft;... // Constructor: protected Foot(String side, int x, int y, int dir) { amLeft = side.equals("left");... } public boolean isLeft() { return amLeft; }... After: public abstract class Foot {... private String mySide;... // Constructor: protected Foot(String side, int x, int y, int dir) { mySide = side;... } public boolean isLeft() { return side.equals("left"); }...

True or False? Abstraction and encapsulation are helpful for the following:  Team development ________  Reusable software ________  GUI programming ________  Easier program maintenance ________

Answer:  Team development ________  Reusable software ________  GUI programming ________  Easier program maintenance ________ T T T (True if you are working on system packages, such as Swing) F

Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding its own. Inheritance represents the is a relationship between data types. For example: a FemaleDancer is a Dancer.

Inheritance Terminology: public class FemaleDancer extends Dancer {... } subclass or derived class superclass or base class extends

Example: Inheritance (cont’d)

public class FemaleDancer extends Dancer { public FemaleDancer(String steps[], int x, int y, int dir) { leftFoot = new FemaleFoot("left", x, y, dir); rightFoot = new FemaleFoot("right", x, y, dir); leftFoot.move(-Foot.getWidth() / 2, 0); rightFoot.move(Foot.getWidth() / 2, 0); } Constructors are not inherited. The FemaleDancer class only adds a constructor:

Example: Inheritance (cont’d)

public class FemaleFoot extends Foot { public FemaleFoot(String side, int x, int y, int dir) { super(side, x, y, dir); // calls Foot's constructor } // public void drawLeft(Graphics g) {... } public void drawRight(Graphics g) {... } Supplies methods that are abstract in Foot :

Inheritance may be used to define a hierarchy of classes in an application:

public class DanceFloor extends JPanel { private DanceModel currentDance; public void updateDance(DanceModel dance) {... }... public void paintComponent(Graphics g) {... } Added method Added field Redefined method Inheritance is also used to extend library classes (or someone else’s classes)

You don’t need to have the source code of a class to extend it (e.g., we don’t need to have JPanel.java to write your DanceFloor class that extends JPanel ) All methods of the base library class are available in your derived class

... DanceFloor extends JPanel Example: public class DanceStudio extends JApplet implements ActionListener { public void init() {... floorPanel = new DanceFloor(); floorPanel.setBackground(Color.white);... }... The setBackground method is inherited from the Swing class JPanel (along with its 287 other methods)

True or False? Inheritance is helpful for the following:  Team development ________  Reusable software ________  GUI programming ________  Easier program maintenance ________

Answer:  Team development ________  Reusable software ________  GUI programming ________  Easier program maintenance ________ F T ??? T

Polymorphism Polymorphism ensures that the appropriate method is called for an object of a specific type when the object is disguised as a more general type. Good news: polymorphism is already supported in Java — all you have to do is use it properly.

Polymorphism (cont’d) Situation 1: A collection (array, list, etc.) contains objects of different but related types, all derived from the same common base class.

public class DanceModel {... public DanceModel(...) { dancers = new Dancer[2]; dancers[0] = new MaleDancer(...); dancers[1] = new FemaleDancer(...);... }... } Example: 

public class DanceFloor extends JPanel {... public void paintComponent(Graphics g) {... Dancer dancer; for (int k = 0; (dancer = currentDance.getDancer(k)) != null; k++) dancer.draw(g); } Example (cont’d):

Polymorphism (cont’d) Situation 2: Abstract class’s fields are instantiated in concrete subclasses.

public abstract class Dancer { protected Foot leftFoot; protected Foot rightFoot;... public void draw(Graphics g) { leftFoot.draw(g); rightFoot.draw(g); } What kind of feet, male or female? This is unknown at compile time Example: The correct “draw” will be called for the male or female feet, depending on the particular dancer

public class FemaleDancer extends Dancer { public FemaleDancer(int x, int y, int dir) { leftFoot = new FemaleFoot("left", x, y, dir); rightFoot = new FemaleFoot("right", x, y, dir);... } Example (cont’d):

public abstract class Foot {... public void draw(Graphics g) {... if (isLeft()) drawLeft(g); else drawRight(g);... } Polymorphism replaces old-fashioned use of explicit object attributes and if-else (or switch ) statements, as in:

Java: