62
Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy, Andover, MA [email protected]

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

Embed Size (px)

DESCRIPTION

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.”

Citation preview

Page 1: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Abstraction, Inheritance, and Polymorphism

in the Dance Studio in Java

Maria LitvinPhillips Academy, Andover, [email protected]

Page 2: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Why is The College Board using Java?

Three reasons:• OOP• OOP• OOP

Java:

Page 3: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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.”

Page 4: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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... :)

Page 5: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 6: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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)

Page 7: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 8: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

OOP

Page 9: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Case Study: Dance Studio

Page 10: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Exercise 1:

Run the Dance Studio applet.

Page 11: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Exercise 2:

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

Page 12: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Quiz:

How many classes were writtenfor this applet?

A. 1B. 2C. 5D. 10E. 17

Page 13: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

DanceStudio

DanceModel

Music

DanceFloor

Controller

Model

View

MaleDancerFemaleDancer

MaleFootFemaleFoot

Dancer

Foot

Page 14: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Good news:The classes are fairly short

DanceStudio 92 lines MaleDancer 10 lines

DanceModel 50 lines FemaleDancer 10 lines

DanceFloor 30 lines Foot 100 lines

Music 52 lines MaleFoot 42 lines

Dancer 80 lines FemaleFoot 42 lines

• In OOP, the number of classes is not considered a problem

Page 15: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

How many Java/Swing library classes are used, explicitly or implicitly, in this applet?

A. 4B. 8C. 12D. 20-50E. 100-500

Quiz:

Page 16: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Answer: E (hundreds)

Page 17: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

/* * @(#)JButton.java 1.83 00/03/14 * Copyright 1997-2000 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;...

Page 18: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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?

Page 19: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Abstraction

MaleDancer FemaleDancer

Dancer

Page 20: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 21: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 22: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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() { ... }}

Page 23: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 24: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

DanceModel (cont’d...)

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

Page 25: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

DanceStudio

DanceModel

Music

DanceFloor

MaleDancerFemaleDancer

MaleFootFemaleFoot

Dancer

Foot

Page 26: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 27: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Hint:

• In DanceModel, add a MaleDancer and a FemaleDancer as follows:

0

2

4

6x

y

Dancer’s position

(in pixels)

dancer[...] = new MaleDancer(x, y, dir);

Dancer’s orientation

Page 28: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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.

Page 29: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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"

Page 30: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

EncapsulationEncapsulation 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.

Page 31: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Encapsulation

MaleFoot FemaleFoot

Foot

Page 32: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 33: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Foot (cont’d...)

// Public methods -- accessors:

public static int getWidth() { return footWidth; }

public boolean isLeft() { return amLeft; }

Continued

Page 34: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Foot (cont’d...)

public int getX() { return myX; }

public int getY() { return myY; }

public int getDir() { return myDir; }

public boolean hasWeight() { return myWeight; }

Continued

Page 35: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 36: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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);}

Page 37: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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”)

Page 38: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Encapsulation (cont’d)

Example:

Suppose in Foot we decided to use private String mySide;

instead ofprivate boolean amLeft;

Page 39: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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"); } ...

Page 40: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

True or False? Abstraction and encapsulation are helpful for the following:

Team development ________

Reusable software ________

GUI programming ________

Easier program maintenance ________

Page 41: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 42: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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.

Page 43: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Inheritance Terminology:

public class FemaleDancer extends Dancer{ ...}

subclass

or

derived class

superclass

or

base class

extends

Page 44: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

MaleDancer FemaleDancer

Dancer

Example:

Inheritance (cont’d)

Page 45: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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:

Page 46: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

MaleFoot FemaleFoot

Foot

Example:

Inheritance (cont’d)

Page 47: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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:

Page 48: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

MaleFoot FemaleFoot

Foot

MaleLeftFoot MaleRightFoot FemaleLeftFoot FemaleRightFoot

Object

Page 49: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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)

Page 50: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

• 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

Page 51: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

... 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)

Page 52: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

True or False? Inheritance is helpful for the following:

Team development ________

Reusable software ________

GUI programming ________

Easier program maintenance ________

Page 53: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Answer:

Team development ________

Reusable software ________

GUI programming ________

Easier program maintenance ________

F

T

???

T

Page 54: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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.

Page 55: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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.

Page 56: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Example:

Page 57: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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):

Page 58: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Polymorphism (cont’d)

Situation 2:

Abstract class’s fields are instantiated in concrete subclasses.

Page 59: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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

Page 60: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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):

Page 61: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

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:

Page 62: Abstraction, Inheritance, and Polymorphism in the Dance Studio in Java Maria Litvin Phillips Academy,…

Java: