classes

64
Classes

Upload: goldy

Post on 06-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Classes. Preparation. Scene so far has been background material and experience Computing systems and problem solving Variables Types Input and output Expressions Assignments Objects Standard classes and methods. Ready. Experience what Java is really about - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Classes

Classes

Page 2: Classes

Preparation• Scene so far has been background material and experience

– Computing systems and problem solving– Variables– Types– Input and output– Expressions – Assignments– Objects– Standard classes and methods

Page 3: Classes

Ready• Experience what Java is really about

– Design and implement objects representing information and physical world objects

Page 4: Classes

Object-oriented programming• Basis

– Create and manipulate objects with attributes and behaviors that the programmer can specify

• Mechanism– Classes

• Benefits– An information type is design and

implemented once and reused as needed• No need reanalysis and re-justification of the

representation

Page 5: Classes

Design an air conditioner representation

• Context

• Behaviors

• Attributes

Page 6: Classes

Design an air conditioner representation

• Context– Repair person– Sales person– Consumer

• Behaviors

• Attributes

Page 7: Classes

Design an air conditioner representation

• Context – Consumer

• Behaviors

• Attributes

Page 8: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting

– Build – construction– Debug

• Attributes

Page 9: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting

– Build – construction– Debug – to stringing

• Attributes

Page 10: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting – mutation

– Build – construction– Debug – to stringing

• Attributes

Page 11: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – accessing – Set temperature and fan setting – mutation

– Build – construction– Debug – to stringing

• Attributes

Page 12: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on – mutation – Turn off – mutation – Get temperature and fan setting – accessing – Set temperature and fan setting – mutation

– Build – construction– Debug – to stringing

• Attributes

Page 13: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on – mutation – Turn off – mutation – Get temperature and fan setting – accessing – Set temperature and fan setting – mutation

– Build – construction– Debug – to stringing

• Attributes

Page 14: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting

– Build -- construction– Debug

• Attributes– Power setting– Fan setting– Temperature setting

Page 15: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting

– Build -- construction– Debug

• Attributes– Power setting– Fan setting– Temperature setting – integer

Page 16: Classes

Design an air conditioner representation• Context - Consumer

• Behaviors– Turn on– Turn off– Get temperature and fan setting – Set temperature and fan setting

– Build -- construction– Debug

• Attributes– Power setting – binary – Fan setting – binary – Temperature setting – integer

Page 17: Classes

Design an air conditioner representation

// Represent an air conditioner – from consumer view point

public class AirConditioner {

// instance variables

// constructors

// methods

}

• Source AirConditioner.java

Page 18: Classes

Static variables and constants

// shared resource for all AirConditioner objectsstatic public final int OFF = 0;Static public final int ON = 1;static public final int LOW = 0;Static public final int HIGH = 1;static public final int DEFAULT_TEMP = 72;

• Every object in the class has access to the same static variables and constants– A change to a static variable is visible to all of the objects in

the class

– Examples StaticDemo.java and DemoStatic.java

Page 19: Classes

Instance variables

// individual object attributesint powerSetting;int fanSetting;int temperatureSetting;

• Instance variables are always initialized as soon the object comes into existence– If no value is specified

• 0 used for numeric variables• false used for logical variables• null used for object variables

• Examples InitializeDemo.java

Page 20: Classes

Constructors

// AirConditioner(): default constructorpublic AirConditioner() {

this.powerSetting = AirConditioner.OFF;this.fanSetting = AirConditioner.LOW;this.temperatureSetting = AirConditioner.DEFAULT_TEMP;

}

// AirConditioner(): specific constructorpublic AirConditioner(int myPower, int myFan, int myTemp) {

this.powerSetting = myPower;this.fanSetting = myFan;this.temperatureSetting = myTemp;

}

• Example AirConditionerConstruction.java

Page 21: Classes

Simple mutators

// turnOn(): set the power setting to onpublic void turnOn() {

this.powerSetting = AirConditioner.ON;}

// turnOff(): set the power setting to offpublic void turnOff() {

this.powerSetting = AirConditioner.OFF;}

• Example TurnDemo.java

Page 22: Classes

Simple accessors// getPowerStatus(): report the power settingpublic int getPowerStatus() {

return this.powerSetting;}

// getFanStatus(): report the fan settingpublic int getFanStatus() {

return this.fanSetting;}

// getTemperatureStatus(): report the temperature settingpublic int getTemperatureStatus () {

return this.temperatureSetting;}

• Example AirConditionerAccessors.java

Page 23: Classes

Parametric mutators// setPower(): set the power setting as indicatedpublic void setPower(int desiredSetting) {

this.powerSetting = desiredSetting;}

// setFan(): set the fan setting as indicatedpublic void setFan(int desiredSetting) {

this.fanSetting = desiredSetting;}

// setTemperature(): set the temperature setting as indicatedpublic void setTemperature(int desiredSetting) {

this.temperatureSetting = desiredSetting;}

• Example AirConditionerSetMutation.java

Page 24: Classes

Facilitator toString()

// toString(): produce a String representation of the objectpublic String toString() {

String result = "[ power: " + this.powerSetting + ", fan: " + this.fanSetting + ", temperature: " +

this.temperatureSetting + " ] ";

return result;}

Page 25: Classes

Sneak peek facilitator toString()public String toString() {

String result = "[ power: " ;

if ( this.powerSetting == AirConditioner.OFF ) {result = result + "OFF";

}else {

result = result + "ON " ;}

result = result + ", fan: ";if ( this.fanSetting == AirConditioner.LOW ) {

result = result + "LOW ";}else {

result = result + "HIGH";}

result = result + ", temperature: " + this.temperatureSetting + " ]";

return result;}

Page 26: Classes
Page 27: Classes

ColoredRectangle • Purpose

– Represent a colored rectangle in a window– Introduce the basics of object design and implementation

Page 28: Classes

Background• JFrame

– Principal Java class for representing a titled, bordered graphical window.

– Standard class• Part of the swing library

import javax.swing.* ;

Page 29: Classes

Example• Consider

JFrame w1 = new JFrame("Bigger");JFrame w2 = new JFrame("Smaller");w1.setSize(200, 125);w2.setSize(150, 100);w1.setVisible(true);w2.setVisible(true);

Page 30: Classes

Example• Consider

JFrame w1 = new JFrame("Bigger");JFrame w2 = new JFrame("Smaller");w1.setSize(200, 125);w2.setSize(150, 100);w1.setVisible(true);w2.setVisible(true);

Page 31: Classes

Example• Consider

JFrame w1 = new JFrame("Bigger");JFrame w2 = new JFrame("Smaller");w1.setSize(200, 125);w2.setSize(150, 100);w1.setVisible(true);w2.setVisible(true);

Page 32: Classes

Example• Consider

JFrame w1 = new JFrame("Bigger");JFrame w2 = new JFrame("Smaller");w1.setSize(200, 125);w2.setSize(150, 100);w1.setVisible(true);w2.setVisible(true);

200 pixels 150 pixels

125pixels

100pixels

Page 33: Classes

Class ColoredRectangle – initial version• Purpose

– Support the display of square window containing a blue filled-in rectangle• Window has side length of 200 pixels• Rectangle is 40 pixels wide and 20 pixels high• Upper left hand corner of rectangle is at (80, 90)

– Limitations are temporary• Remember BMI.java preceded BMICalculator.java• Lots of concepts to introduce

Page 34: Classes

ColoredRectangle in action• Consider

ColoredRectangle r1 = new ColoredRectangle();ColoredRectangle r2 = new ColoredRectangle();

System.out.println("Enter when ready");System.in.read();

r1.paint(); // draw the window associated with r1r2.paint(); // draw the window associated with r2

Page 35: Classes

ColoredRectangle in action• Consider

ColoredRectangle r1 = new ColoredRectangle();ColoredRectangle r2 = new ColoredRectangle();

System.out.println("Enter when ready");System.in.read();

r1.paint(); // draw the window associated with r1r2.paint(); // draw the window associated with r2

Page 36: Classes

ColoredRectangle in action• Consider

ColoredRectangle r1 = new ColoredRectangle();ColoredRectangle r2 = new ColoredRectangle();

System.out.println("Enter when ready");System.in.read();

r1.paint(); // draw the window associated with r1r2.paint(); // draw the window associated with r2

Page 37: Classes

ColoredRectangle in action• Consider

ColoredRectangle r1 = new ColoredRectangle();ColoredRectangle r2 = new ColoredRectangle();

System.out.println("Enter when ready");System.in.read();

r1.paint(); // draw the window associated with r1r2.paint(); // draw the window associated with r2

r1.paint()The messages instruct the objects to display themselves

r2.paint()

ColoredRectangle object referenced by r1 is being sent a message

ColoredRectangle object referenced by r2 is being sent a message

Page 38: Classes

ColoredRectangle.java outline

import javax.swing.*;import java.awt.*;

public class ColoredRectangle {// instance variables for holding object attributesprivate int width; private int height; private int x;private int y;private JFrame window;private Color color;

// ColoredRectangle(): default constructorpublic ColoredRectangle() { // ...}// paint(): display the rectangle in its windowpublic void paint() { // ...}

}

Page 39: Classes

Instance variables and attributes• Data field

– Java term for an object attribute

• Instance variable– Symbolic name for a data field

– Usually has private access• Assists in information hiding by encapsulating the

object’s attributes

– Default initialization• Numeric instance variables initialized to 0• Logical instance variables initialized to false• Object instance variables initialized to null

Page 40: Classes

public class ColoredRectangle {

// instance variables for holding object attributesprivate int width; private int x;private int height; private int y;private JFrame window; private Color color;// ColoredRectangle(): default constructorpublic ColoredRectangle() {

window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20; y = 90;color = Color.BLUE;window.setVisible(true);

}// paint(): display the rectangle in its windowpublic void paint() {

Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}}

Page 41: Classes

public class ColoredRectangle {

// instance variables for holding object attributesprivate int width; private int x;private int height; private int y;private JFrame window; private Color color;// ColoredRectangle(): default constructorpublic ColoredRectangle() {

window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20; y = 90;color = Color.BLUE;window.setVisible(true);

}// paint(): display the rectangle in its windowpublic void paint() {

Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}}

Page 42: Classes

ColoredRectangle default constructor

public class ColoredRectangle {// instance variables to describe object attributes...

// ColoredRectangle(): default constructorpublic ColoredRectangle() {

...

}...

}

A constructor does not list its return type. A constructoralways returns a reference to a new object of its class

The name of a constructor always matches thename of its class

Page 43: Classes

public class ColoredRectangle {

// instance variables for holding object attributesprivate int width; private int x;private int height; private int y;private JFrame window; private Color color;// ColoredRectangle(): default constructorpublic ColoredRectangle() {

window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20; y = 90;color = Color.BLUE;window.setVisible(true);

}// paint(): display the rectangle in its windowpublic void paint() {

Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}}

Page 44: Classes

Color constants• Color.BLACK• Color.BLUE • Color.CYAN • Color.DARK_GRAY • Color.GRAY • Color.GREEN• Color.LIGHT_GRAY• Color.MAGENTA• Color.ORANGE• Color.PINK • Color.RED • Color.WHITE • Color.YELLOW

Page 45: Classes

r

The value of aColoredRectangle

variable is areference to a

ColoredRectangleobject

+ paint() : void

ColorRectangle

- width = 40- height = 20- x = 80- y = 90- window =- color =

Color

- color =- ...

+ brighter() : Color+ ...

+ setVisible(boolean status) : void+ ...

JFrame

- width = 200- height = 200- title =- ...

String

- text = "Box Fun"- ...

+ length() : int+ ...

ColoredRectangle r = new ColoredRectangle();

Page 46: Classes

public class ColoredRectangle {

// instance variables for holding object attributesprivate int width; private int x;private int height; private int y;private JFrame window; private Color color;// ColoredRectangle(): default constructorpublic ColoredRectangle() {

window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20; y = 90;color = Color.BLUE;window.setVisible(true);

}// paint(): display the rectangle in its windowpublic void paint() {

Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}}

Page 47: Classes

Graphical context• Graphics

– Defined in java.awt.Graphics– Represents the information for a rendering request

• Color• Component• Font• …

– Provides methods– Text drawing

• Line drawing• Shape drawing

– Rectangles– Ovals– Polygons

Page 48: Classes

Java coordinate system

Coordinate (80, 90)

Coordinate (0.0)

X-Axis

Y-A

xis

Coordinate (120, 110)

Page 49: Classes

public class ColoredRectangle {

// instance variables for holding object attributesprivate int width; private int x;private int height; private int y;private JFrame window; private Color color;// ColoredRectangle(): default constructorpublic ColoredRectangle() {

window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20; y = 90;color = Color.BLUE;window.setVisible(true);

}// paint(): display the rectangle in its windowpublic void paint() {

Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}}

Page 50: Classes

Method invocation• Consider

r1.paint(); // display window associated with r1r2.paint(); // display window associated with r2

• Observe– When an instance method is being executed, the attributes

of the object associated with the invocation are accessed and manipulated

– Important that you understand what object is being manipulated

Page 51: Classes

Method invocation

public class ColoredRectangle {// instance variables to describe object attributes...

// paint(): display the rectangle in its windowpublic void paint() {

window.setVisible(true);Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);

}...

}

Instance variable window referencesthe J Frame attribute of the objectthat caused the invocation. That is,the invocation r1.paint() causes thewindow attribute of the Colored-Rectangle referenced by r1 to be

accessed. Similarly, the invocationr2.paint() causes the window

attribute of the ColoredRectanglereferenced by r2 to be accessed.

The values of these instancevariables are also from the

ColoredRectangle object thatinvoked method paint().

Page 52: Classes

Improving ColoredRectangle• Analysis

– A ColoredRectangle object should• Be able to have any color• Be positionable anywhere within its window• Have no restrictions on its width and height• Accessible attributes• Updateable attributes

Page 53: Classes

Improving ColoredRectangle• Additional constructions and behaviors

– Specific construction• Construct a rectangle representation using supplied

values for its attributes

– Accessors• Supply the values of the attributes• Individual methods for providing the width, height, x-

coordinate position, y-coordinate position, color, or window of the associated rectangle

– Mutators• Manage requests for changing attributes• Ensure objects always have sensible values• Individual methods for setting the width, height, x-

coordinate position, y-coordinate position, color, or window of the associated rectangle to a given value

Page 54: Classes

A mutator method• Definition

// setWidth(): width mutatorpublic void setWidth(int w) {

width = w;}

• Usage

Col or edRect angl e s = new Col or edRect angl e( ) ;s. set Wi dt h( 80) ;

publ i c voi d set Wi dt h( i nt w) {. . .

}

Initial value of the formal parametercomes from the actual parameter

Changes to the formal parameterdo not affect the actual parameter

Object to be manipulatedis the one referenced by s

Page 55: Classes

Mutator setWidth() evaluationColoredRectangle s = new ColoredRectangle();s.setWidth(80);

public class ColoredRectangle {...// setWidth(): width mutatorpublic void setWidth(int w) {

width = w;}

...}

The invocation sends a message to the ColoredRectanglereferenced by s to modify its width attribute. To do so,there is a temporary transfer of flow of control tosetWidth(). The value of the actual parameter is 80

Method setWidth() sets the instance variable width of itsColoredRectangle. For this invocation, width is set to 80and the ColoredRectangle is the one referenced by s

For this invocation of methodsetWidth(), w is initialized to80. The object being referencedwithin the method body is theobject referenced by s

Method setWidth() is completed. Control is transferred back tothe statement that invoked setWidth()

Page 56: Classes

Subtleties• Consider

ColoredRectangle r = new ColoredRectangle();r.paint(); r.setWidth(80); r.paint();

• What is the width is the rectangle on the screen after the mutator executes?

Page 57: Classes

Other mutatorspublic void setHeight(int h) {

height = h;}

public void setX(int ulx) {x = ulx;

}

public void setY(int uly) {y = uly;

}

public void setWindow(JFrame f) {window = f;

}

public void setColor(Color c) {color = c;

}

Page 58: Classes

Mutator usage

ColoredRectangle u = new ColoredRectangle();ColoredRectangle v = new ColoredRectangle();u.setHeight(100);u.setColor(Color.PINK);v.setX(25);v.setY(50);JFrame display =

new JFrame("Fun");v.setWindow(display);

Sends a message to v's Colored-Rectangle to modify its windowattribute to display's J Frame

Sends a message tou's ColoredRectangleto modify its heightattribute to 100

Sends a message to u's Colored-Rectangle to modify its colorattribute to pink

Sends a message to v's Colored-Rectangle to modify its x-axisposition to 25

Sends a message to v's Colored-Rectangle to modify its y-axisposition to 50

Page 59: Classes

Accessors• Properties

– Do not require parameters– Each accessor execution produces a return value

• Return value is the value of the invocation

public int getWidth() {return width;

}

The method return type precedes the name of the method in themethod definition

For method getWidth(), the return value is the value of the widthattribute for the ColoredRectangle associated with the invocation.In invocation t.getWidth(), the return value is the value of theinstance variable width for the ColoredRectangle referenced by t

Page 60: Classes

Accessor usage

ColoredRectangle t = new ColoredRectangle();int w = t.getWidth();

public class ColoredRectangle {...// getWidth(): accessorpublic int getWidth() {

return width;}

...}

Invocation sends a message to the ColoredRectanglereferenced by t to return the value of its width. To do so,there is a temporary transfer of flow of control to getWidth()

The return expression evaluates to 40 (the widthattribute of the ColoredRectangle object referenced by t )

Method getWidth() starts executing.For this invocation, the object beingreferenced is the object referenced by t

Method completes by supplying its return value (40) to the invokingstatement. Also, invoking statement regains the flow of control. Fromthere variable w is initialized with the return value of the invocatio

Page 61: Classes

Specific constructionpublic ColoredRectangle(int w, int h, int ulx, int uly,

JFrame f, Color c) {

setWidth(w);setHeight(h);setX(ulx);setY(uly);setWindow(f);setColor(c);

}

• Requires values for each of the attributesJFrame display = new JFrame("Even more fun");display.setSize(400, 400);ColoredRectangle w = new ColoredRectangle(60, 80,

20, 20, display, Color.YELLOW);

Page 62: Classes

Specific constructionpublic ColoredRectangle(int w, int h, int ulx, int uly,

JFrame f, Color c) {

setWidth(w);setHeight(h);setX(ulx);setY(uly);setWindow(f);setColor(c);

}

• Advantages to using mutators– Readability– Less error prone– Facilitates enhancements through localization

Page 63: Classes

Seeing doubleimport java.io.*;import java.awt.*;

public class SeeingDouble {

public static void main(String[] args)throws IOException {

ColoredRectangle r = new ColoredRectangle();

System.out.println("Enter when ready");System.in.read();

r.paint();

r.setY(50);r.setColor(Color.RED);r.paint();

}}

Page 64: Classes

Seeing double