1 even even more on being classy aaron bloomfield cs 101-e chapter 4+

Post on 04-Jan-2016

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

11

Even even more Even even more on being classyon being classy

Aaron BloomfieldAaron Bloomfield

CS 101-ECS 101-E

Chapter 4+Chapter 4+

22

Consider this sequence of events…Consider this sequence of events…

33

What happened?What happened?

Java didn’t “repaint” the rectangles when Java didn’t “repaint” the rectangles when necessarynecessaryJava only painted the rectangle onceJava only painted the rectangle once

You can tell Java to repaint it whenever You can tell Java to repaint it whenever necessarynecessaryThis is beyond the scope of this class, though!This is beyond the scope of this class, though!

44

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

public class SeeingDouble {public class SeeingDouble {

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

ColoredRectangle r = new ColoredRectangle();ColoredRectangle r = new ColoredRectangle();

System.out.println("Enter when ready");System.out.println("Enter when ready");Scanner stdin = new Scanner (System.in);Scanner stdin = new Scanner (System.in);stdin.nextLine();stdin.nextLine();

r.paint();r.paint();

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

}}}}

55

Seeing doubleSeeing double

When paint() was called, the previous When paint() was called, the previous rectangle was not erasedrectangle was not erasedThis is a simpler way of implementing thisThis is a simpler way of implementing this

Perhaps clear and repaint everything Perhaps clear and repaint everything when a rectangle paint() is calledwhen a rectangle paint() is called

66

// Purpose: Create two windows containing colored rectangles.// Purpose: Create two windows containing colored rectangles.

import java.util.*;import java.util.*;

public class BoxFun {public class BoxFun {

//main(): application entry point//main(): application entry pointpublic static void main (String[] args) {public static void main (String[] args) {

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

System.out.println("Enter when ready");System.out.println("Enter when ready");Scanner stdin = new Scanner (System.in);Scanner stdin = new Scanner (System.in);stdin.nextLine();stdin.nextLine();

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

}}}}

Code from last classCode from last class

77

public class ColoredRectangle {public class ColoredRectangle {

// instance variables for holding object attributes// instance variables for holding object attributes

private int width; private int width; private int x; private int x;

private int height; private int height; private int y; private int y;

private JFrame window; private JFrame window; private Color color; private Color color;

// ColoredRectangle(): default constructor// ColoredRectangle(): default constructor

public ColoredRectangle() {public ColoredRectangle() {

color = Color.BLUE;color = Color.BLUE;

width = 40; width = 40; x = 80;x = 80;

height = 20;height = 20; y = 90;y = 90;

window = new JFrame("Box Fun");window = new JFrame("Box Fun");

window.setSize(200, 200);window.setSize(200, 200);

window.setVisible(true);window.setVisible(true);

}}

// paint(): display the rectangle in its window// paint(): display the rectangle in its window

public void paint() {public void paint() {

Graphics g = window.getGraphics();Graphics g = window.getGraphics();

g.setColor(color);g.setColor(color);

g.fillRect(x, y, width, height);g.fillRect(x, y, width, height);

}}

}}

88

String

- text = “Box Fun”

- ...

+ length() : int + ...

+ setVisible (boolean status) : void+ getGraphics () : Graphics+ setSize (int w, int h) : void+ …

JFrame

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

Graphics

- …

+ setColor(Color) : void + ...

+ fillRect() : void

r

+ paint() : void

ColorRectangle

- width = 0- height = 0- x = 0- y = 0- color =- window =

Color

- color =- ...

+ brighter() : Color+ ...

ColoredRectangle r = new ColoredRectangle();

+ paint() : void

ColorRectangle

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

public class public class ColoredRectangle {ColoredRectangle {

private int width;private int width;

private int x, y;private int x, y;

private int height;private int height;

private int y;private int y;

private JFrame window;private JFrame window;

private Color color;private Color color;

public ColoredRectangle() {public ColoredRectangle() { color = Color.BLUE;color = Color.BLUE; width = 40;width = 40; height = 20;height = 20; y = 90;y = 90; x = 80;x = 80; window = new window = new

JFrameJFrame("Box Fun");("Box Fun");

window.setSizewindow.setSize(200, 200);(200, 200);

window.setVisiblewindow.setVisible(true);(true);

}}

public void paint() {public void paint() {

Graphics g = Graphics g =

window.getGraphics();window.getGraphics();

g.setColor(color);g.setColor(color);

g.fillRect (x, y, g.fillRect (x, y,

width, height);width, height);

}}

g

99

The Vector classThe Vector class

In java.utilIn java.utilMust put “import java.util.*;” in the java fileMust put “import java.util.*;” in the java file

Probably the most useful class in the Probably the most useful class in the library (in my opinion)library (in my opinion)

A Vector is a collection of “things” (objects)A Vector is a collection of “things” (objects) It has nothing to do with the geometric vectorIt has nothing to do with the geometric vector

1010

Vector methodsVector methods

Constructor: Vector()Constructor: Vector()Adding objects: add (Object o);Adding objects: add (Object o);Removing objects: remove (int which)Removing objects: remove (int which)Number of elements: size()Number of elements: size()Element access: elementAt()Element access: elementAt()Removing all elements: clear()Removing all elements: clear()

1111

Vector code exampleVector code exampleVector v = new Vector();Vector v = new Vector();System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.add ("first");v.add ("first");System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.add ("second");v.add ("second");v.add ("third");v.add ("third");System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

String s = (String) v.elementAt (2);String s = (String) v.elementAt (2);System.out.println (s);System.out.println (s);

String t = (String) v.elementAt (3);String t = (String) v.elementAt (3);System.out.println (t);System.out.println (t);

v.remove (1);v.remove (1);System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.clear();v.clear();System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

0 []0 []

1 [first]1 [first]

3 [first, second, third]3 [first, second, third]

thirdthird

(Exception) (Exception)

2 [first, third]2 [first, third]

0 []0 []

1212

What we wish computers could doWhat we wish computers could do

1313

The usefulness of VectorsThe usefulness of Vectors

You can any object to a VectorYou can any object to a VectorStrings, ColoredRectanges, JFrames, etc.Strings, ColoredRectanges, JFrames, etc.

They are not the most efficient for some They are not the most efficient for some taskstasksSearching, in particularSearching, in particular

1414

About that exception…About that exception…

The exact exception was:The exact exception was:

Exception in thread "main" Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 >= 3java.lang.ArrayIndexOutOfBoundsException: 3 >= 3

at java.util.Vector.elementAt(Vector.java:431)at java.util.Vector.elementAt(Vector.java:431)

at VectorTest.main(VectorTest.java:15)at VectorTest.main(VectorTest.java:15)

Where the problem occured

1515

A Vector of intsA Vector of ints Consider the following code:Consider the following code:

Vector v = new Vector();Vector v = new Vector();v.add (1);v.add (1);

Causes a compile-time errorCauses a compile-time error Most of the time - see disclaimer laterMost of the time - see disclaimer later

C:\Documents and Settings\Aaron\My Documents\C:\Documents and Settings\Aaron\My Documents\JCreator\VectorTest\VectorTest.java:7: cannot JCreator\VectorTest\VectorTest.java:7: cannot resolve symbolresolve symbol

symbol : method add (int)symbol : method add (int)location: class java.util.Vectorlocation: class java.util.Vector

v.add (1);v.add (1);

1616

What happened?What happened?

The Vector add() method:The Vector add() method:boolean add(Object o)boolean add(Object o)

Primitive types are not objects!Primitive types are not objects!

Solution: use wrapper classes!Solution: use wrapper classes!

1717

More on wrapper classesMore on wrapper classes

A wrapper class allows a primitive type to act as A wrapper class allows a primitive type to act as an objectan object

Each primitive type has a wrapper class:Each primitive type has a wrapper class: BooleanBoolean CharacterCharacter ByteByte ShortShort

Note that char and int don’t have the exact same Note that char and int don’t have the exact same name as their wrapper classesname as their wrapper classes

IntegerInteger LongLong FloatFloat DoubleDouble

1818

Vector code exampleVector code exampleVector v = new Vector();Vector v = new Vector();System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.add (new Integer(1));v.add (new Integer(1));System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.add (new Integer(2));v.add (new Integer(2));v.add (new Integer(3));v.add (new Integer(3));System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

Integer s = (Integer) v.elementAt (2);Integer s = (Integer) v.elementAt (2);System.out.println (s);System.out.println (s);

Integer t = (Integer) v.elementAt (3);Integer t = (Integer) v.elementAt (3);System.out.println (t);System.out.println (t);

v.remove (1);v.remove (1);System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

v.clear();v.clear();System.out.println (v.size() + " " + v);System.out.println (v.size() + " " + v);

0 []0 []

1 [1]1 [1]

3 [1, 2, 3]3 [1, 2, 3]

33

(Exception) (Exception)

2 [1, 3]2 [1, 3]

0 []0 []

1919

Even more on wrapper classesEven more on wrapper classes

They have useful class (i.e. static) They have useful class (i.e. static) variables:variables: Integer.MAX_VALUEInteger.MAX_VALUEDouble.MIN_VALUEDouble.MIN_VALUE

They have useful methods:They have useful methods:String s = “3.14159”;String s = “3.14159”;double d = Double.parseDouble (s);double d = Double.parseDouble (s);

2020

A disclaimerA disclaimer

Java 1.5 (which we are not using) has a Java 1.5 (which we are not using) has a new feature called “autoboxing/unboxing”new feature called “autoboxing/unboxing”

This will automatically convert primitive This will automatically convert primitive types to their wrapper classes (and back)types to their wrapper classes (and back)

2121

An optical illusionAn optical illusion

2222

Design an air conditioner Design an air conditioner representationrepresentation

ContextContext Repair personRepair person Sales personSales person ConsumerConsumer

BehaviorsBehaviors

AttributesAttributes

- Consumer- Consumer

2323

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting Set temperature and fan setting

Build – Build – constructionconstruction DebugDebug

AttributesAttributes

2424

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting Set temperature and fan setting

Build – constructionBuild – construction Debug – Debug – to stringingto stringing

AttributesAttributes

2525

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting – Set temperature and fan setting – mutationmutation

Build – constructionBuild – construction Debug – to stringingDebug – to stringing

AttributesAttributes

2626

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting – Get temperature and fan setting – accessingaccessing Set temperature and fan setting – mutation Set temperature and fan setting – mutation

Build – constructionBuild – construction Debug – to stringingDebug – to stringing

AttributesAttributes

2727

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn on – Turn on – mutationmutation Turn off – Turn off – mutationmutation Get temperature and fan setting – accessing Get temperature and fan setting – accessing Set temperature and fan setting – mutation Set temperature and fan setting – mutation

Build – constructionBuild – construction Debug – to stringingDebug – to stringing

AttributesAttributes

2828

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

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

Build – constructionBuild – construction Debug – to stringingDebug – to stringing

AttributesAttributes

2929

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting Set temperature and fan setting

Build -- constructionBuild -- construction DebugDebug

AttributesAttributes Power settingPower setting Fan settingFan setting Temperature settingTemperature setting

3030

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting Set temperature and fan setting

Build -- constructionBuild -- construction DebugDebug

AttributesAttributes Power settingPower setting Fan settingFan setting Temperature setting – Temperature setting – integerinteger

3131

Design an air conditioner Design an air conditioner representationrepresentation

Context - ConsumerContext - Consumer

BehaviorsBehaviors Turn onTurn on Turn offTurn off Get temperature and fan setting Get temperature and fan setting Set temperature and fan setting Set temperature and fan setting

Build -- constructionBuild -- construction DebugDebug

AttributesAttributes Power setting – Power setting – binarybinary Fan setting – Fan setting – binarybinary Temperature setting – integer Temperature setting – integer

3232

Ugh…Ugh…

3333

Design an air conditioner Design an air conditioner representationrepresentation

// Represent an air conditioner – from consumer view point// Represent an air conditioner – from consumer view point

public class AirConditioner {public class AirConditioner {

// instance variables// instance variables

// constructors// constructors

// methods// methods

}}

Source Source AirConditioner.javaAirConditioner.java

3434

Static variables and constantsStatic variables and constants

// shared resource for all AirConditioner objects// shared resource for all AirConditioner objects

static public final int OFF = 0;static public final int OFF = 0;

Static public final int ON = 1;Static public final int ON = 1;

static public final int LOW = 0;static public final int LOW = 0;

Static public final int HIGH = 1;Static public final int HIGH = 1;

static public final int DEFAULT_TEMP = 72;static public final int DEFAULT_TEMP = 72;

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

Examples Examples StaticDemo.javaStaticDemo.java and and DemoStatic.javaDemoStatic.java

3535

Instance variablesInstance variables

// individual object attributes// individual object attributes

int powerSetting;int powerSetting;

int fanSetting;int fanSetting;

int temperatureSetting;int temperatureSetting;

Instance variables are always initialized as soon the object comes into Instance variables are always initialized as soon the object comes into existenceexistence If no value is specifiedIf no value is specified

0 used for numeric variables0 used for numeric variables false used for logical variablesfalse used for logical variables null used for object variablesnull used for object variables

Examples Examples InitializeDemo.javaInitializeDemo.java

3636

ConstructorsConstructors

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

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

}}

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

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

}}

Example Example AirConditionerConstruction.javaAirConditionerConstruction.java

3737

Simple mutatorsSimple mutators

// turnOn(): set the power setting to on// turnOn(): set the power setting to on

public void turnOn() {public void turnOn() {this.powerSetting = AirConditioner.ON;this.powerSetting = AirConditioner.ON;

}}

// turnOff(): set the power setting to off// turnOff(): set the power setting to off

public void turnOff() {public void turnOff() {this.powerSetting = AirConditioner.OFF;this.powerSetting = AirConditioner.OFF;

}}

Example Example TurnDemo.javaTurnDemo.java

3838

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

return this.powerSetting;return this.powerSetting;

}}

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

return this.fanSetting;return this.fanSetting;

}}

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

return this.temperatureSetting;return this.temperatureSetting;

}}

Example Example AirConditionerAccessors.javaAirConditionerAccessors.java

3939

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

this.powerSetting = desiredSetting;this.powerSetting = desiredSetting;

}}

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

this.fanSetting = desiredSetting;this.fanSetting = desiredSetting;

}}

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

this.temperatureSetting = desiredSetting;this.temperatureSetting = desiredSetting;

}}

Example Example AirConditionerSetMutation.javaAirConditionerSetMutation.java

4040

Facilitator toString()Facilitator toString()

// toString(): produce a String representation of the object// toString(): produce a String representation of the object

public String toString() {public String toString() {

String result = "[ power: " + this.powerSetting String result = "[ power: " + this.powerSetting

+ ", fan: " + this.fanSetting+ ", fan: " + this.fanSetting

+ ", temperature: " + this.temperatureSetting+ ", temperature: " + this.temperatureSetting

+ " ] ";+ " ] ";

return result;return result;

}}

4141

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

String result = "[ power: " ;String result = "[ power: " ;

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

} else {} else {result = result + "ON " ;result = result + "ON " ;

}}

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

result = result + "LOW ";result = result + "LOW ";

} else {} else {result = result + "HIGH";result = result + "HIGH";

}}

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

return result;return result;}}

4242

What computers were made forWhat computers were made for

NASA’s NASA’s WorldWindWorldWind

See http://learn.arc.nasa.gov/worldwind/See http://learn.arc.nasa.gov/worldwind/

top related