Classes
Download
1 / 53

Classes - PowerPoint PPT Presentation


  • 51 Views
  • Uploaded on

Classes. CS 101-E Chapter 4 Aaron Bloomfield. Announcements. HWs are being renumbered J1, J2, etc., for Java programming assignments C1, C2, etc., for CodeLab assignments HW1 = J1, HW2 = C1, HW3 = C2, etc. HWs J2 and J3 assigned this Wednesday (6 Oct) J2 due next Thursday (14 Oct)

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Classes' - elaine-blair


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Classes

Classes

CS 101-E

Chapter 4

Aaron Bloomfield


Announcements
Announcements

  • HWs are being renumbered

    • J1, J2, etc., for Java programming assignments

    • C1, C2, etc., for CodeLab assignments

    • HW1 = J1, HW2 = C1, HW3 = C2, etc.

  • HWs J2 and J3 assigned this Wednesday (6 Oct)

    • J2 due next Thursday (14 Oct)

    • J3 due following Thursday (21 Oct)

  • HW J4 will be assigned 18 Oct, and due 29 Oct

  • Some CodeLab HWs in there as well

  • Second midterm on 27 Oct

  • No labs this Sunday

    • Can go to another lab with permission

  • Lab quiz grades will be entered by the end of this week


Preparation
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

  • Now: Experience what Java is really about

    • Design and implement objects representing information and physical world objects


Object oriented programming
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

      • Reused as needed

        • No need reanalysis and re-justification of the representation


First class coloredrectangle
First class – ColoredRectangle

  • Purpose

    • Represent a colored rectangle in a window

    • Introduce the basics of object design and implementation


Background
Background

  • JFrame

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

    • Standard class

      • Part of the swing library

        import javax.swing.* ;



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

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

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


Classes

// Purpose: Displays two different windows.

import javax.swing.*;

public class TwoWindows {

// main(): application entry point

public static void main (String[] args) {

JFrame w1 = new JFrame("Bigger");

JFrame w2 = new JFrame("Smaller");

w1.setSize(200, 125);

w2.setSize(150, 100);

w1.setVisible(true);

w2.setVisible(true);

}

}


Class coloredrectangle initial version
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


Coloredrectangle in action
ColoredRectangle in action

  • Consider

    ColoredRectangle r1 = new ColoredRectangle();

    ColoredRectangle r2 = new ColoredRectangle();

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

    Scanner stdin = new Scanner (System.in);

    stdin.nextLine();

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

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

  • Consider

    ColoredRectangle r1 = new ColoredRectangle();

    ColoredRectangle r2 = new ColoredRectangle();

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

    Scanner stdin = new Scanner (System.in);

    stdin.nextLine();

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

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

  • Consider

    ColoredRectangle r1 = new ColoredRectangle();

    ColoredRectangle r2 = new ColoredRectangle();

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

    Scanner stdin = new Scanner (System.in);

    stdin.nextLine();

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

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

  • Consider

    ColoredRectangle r1 = new ColoredRectangle();

    ColoredRectangle r2 = new ColoredRectangle();

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

    Scanner stdin = new Scanner (System.in);

    stdin.nextLine();

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

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


Classes

// Purpose: Create two windows containing colored rectangles.

import java.util.*;

public class BoxFun {

//main(): application entry point

public static void main (String[] args) {

ColoredRectangle r1 = new ColoredRectangle();

ColoredRectangle r2 = new ColoredRectangle();

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

Scanner stdin = new Scanner (System.in);

stdin.nextLine();

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

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

}

}


Coloredrectangle java outline
ColoredRectangle.java outline rectangles.

import javax.swing.*;

import java.awt.*;

public class ColoredRectangle {

// instance variables for holding object attributes

private int width;

private int height;

private int x;

private int y;

private JFrame window;

private Color color;

// ColoredRectangle(): default constructor

public ColoredRectangle() { // ...

}

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

public void paint() { // ...

}

}


Instance variables and attributes
Instance variables and attributes rectangles.

  • 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


Classes

public class ColoredRectangle { rectangles.

// instance variables for holding object attributes

private int width; private int x;

private int height; private int y;

private JFrame window; private Color color;

// ColoredRectangle(): default constructor

public 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 window

public void paint() {

Graphics g = window.getGraphics();

g.setColor(color);

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

}

}



Classes

public class ColoredRectangle { rectangles.

// instance variables for holding object attributes

private int width; private int x;

private int height; private int y;

private JFrame window; private Color color;

// ColoredRectangle(): default constructor

public 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 window

public void paint() {

Graphics g = window.getGraphics();

g.setColor(color);

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

}

}


Color constants
Color constants rectangles.

  • 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


Classes

ColorRectangle rectangles.

- width = 40

- height = 20

- x = 80

The value of a

- y = 90

ColoredRectangle

- window =

variable is a

String

- color =

reference to a

- text

=

"Box

Fun"

ColoredRectangle

void

+ paint() :

- ...

object

int

+ length()

:

+ ...

Color

JFrame

- color =

- width = 200

- ...

- height = 200

- title =

+ brighter() : Color

- ...

+ ...

boolean

void

+ setVisible(

status)

:

+ ...

r

ColoredRectangle r = new ColoredRectangle();


Another possible constructor
Another possible Constructor rectangles.

public class ColoredRectangle {

// instance variables for holding object attributes

private int width = 40; private int x = 80;

private int height = 80; private int y = 90;

private JFrame window; private Color color = Color.BLUE;

// ColoredRectangle(): default constructor

public ColoredRectangle() {

window = new JFrame("Box Fun");

window.setSize(200, 200);

window.setVisible(true);

}


Classes

public class ColoredRectangle { rectangles.

// instance variables for holding object attributes

private int width; private int x;

private int height; private int y;

private JFrame window; private Color color;

// ColoredRectangle(): default constructor

public 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 window

public void paint() {

Graphics g = window.getGraphics();

g.setColor(color);

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

}

}


Graphical context
Graphical context rectangles.

  • 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



Method invocation
Method invocation rectangles.

  • Consider

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

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


Method invocation1

Instance variable window references rectangles.

the JFrame attribute of the object

that caused the invocation.

The values of these instance

variables are also from the

ColoredRectangle object

Method invocation

public class

ColoredRectangle

{

// instance variables to describe object attributes

...

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

public

void

paint() {

true

);

window.setVisible(

Graphics g = window.getGraphics();

g.setColor(color);

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

}

...

}

Typo in book: p. 149 claims paint() is static; it’s not


The ig nobel prizes
The Ig Nobel Prizes rectangles.

  • Medicine

  • Physics

  • Public Health

  • Chemistry

  • Engineering

  • Literature

  • Psychology

  • Economics

  • Peace

  • Biology

"The Effect of Country Music on Suicide.“

For explaining the dynamics of hula-hooping

Investigating the scientific validity of the Five-Second Rule

The Coca-Cola Company of Great Britain

For the patent of the combover

The American Nudist Research Library

It’s easy to overlook things – even a man in a gorilla suit.

The Vatican, for outsourcing prayers to India

The invention of karaoke, thereby providing an entirely new way for people to learn to tolerate each other

For showing that herrings apparently communicate by farting


Wednesday 6 october 2004
Wednesday, 6 October, 2004 rectangles.

  • Computing grades so far

  • HW J2 assigned today, due next Wednesday

  • Lab this week! Must be done by Sunday at 8:30

  • Sunday labs are cancelled due to fall break

    • If you want, send me an e-mail and you can show up to another lab session

  • No office hours Friday

  • Grades so far: use formula

  • HISTORICALLY, the grade range has been:

    • A: 90+, B: 80-89, C: 60-79, D/F: <60


Improving coloredrectangle
Improving ColoredRectangle rectangles.

  • 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


Improving coloredrectangle1
Improving ColoredRectangle rectangles.

  • 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


A mutator method

Initial value of the formal parameter rectangles.

Object to be manipulated

comes from the actual parameter

is the one referenced by s

public void

setWidth

(

int

w

) {

...

Changes to the formal parameter

}

do not affect the actual parameter

A mutator method

  • Definition

    // setWidth(): width mutator

    public void setWidth(int w) {

    width = w;

    }

  • Usage

ColoredRectangle s = new ColoredRectangle();

s.setWidth(80);


Mutator setwidth evaluation

The invocation sends a message to the ColoredRectangle rectangles.

referenced by s to modify its width attribute. To do so,

there is a temporary transfer of flow of control to

setWidth(). The value of the actual parameter is 80

public

class

ColoredRectangle {

For this invocation of method

...

/

/

setWidth(): width mutator

setWidth(), w is initialized to

80. The object being referenced

public void

int

setWidth

(

w) {

within the method body is the

width

= w;

object referenced by s

}

Method setWidth() sets the instance variable width of its

ColoredRectangle. For this invocation, width is set to 80

...

and the ColoredRectangle is the one referenced by s

}

Method setWidth() is completed. Control is transferred back to

the statement that invoked setWidth()

Mutator setWidth() evaluation

new

ColoredRectangle();

ColoredRectangle s =

s

.setWidth(80);


A bit of humor
A bit of humor… rectangles.


Java parameter passing
Java parameter passing rectangles.

  • The value is copied to the method

  • Any changes to the parameter are forgotten when the method returns


Java parameter passing1
Java parameter passing rectangles.

  • Consider the following code:

    static void foobar (int y) {

    y = 7;

    }

    public static void main (String[] args) {

    int x = 5;

    foobar (x);

    System.out.println(x);

    }

  • What gets printed?

formal parameter

actual parameter


Java parameter passing2
Java parameter passing rectangles.

  • Consider the following code:

    static void foobar (String y) {

    y = “7”;

    }

    public static void main (String[] args) {

    String x = “5”;

    foobar (x);

    System.out.println(x);

    }

  • What gets printed?

formal parameter

actual parameter


Java parameter passing3
Java parameter passing rectangles.

  • Consider the following code:

    static void foobar (ColoredRectangle y) {

    y.setWidth (10);

    }

    public static void main (String[] args) {

    ColoredRectangle x = new ColoredRectangle();

    foobar (x);

    System.out.println(y.getWidth());

    }

  • What gets printed?

formal parameter

actual parameter


Java parameter passing4
Java parameter passing rectangles.

  • Consider the following code:

    static void foobar (ColoredRectangle y) {

    y = new ColoredRectangle();

    y.setWidth (10);

    }

    public static void main (String[] args) {

    ColoredRectangle x = new ColoredRectangle();

    foobar (x);

    System.out.println(y.getWidth());

    }

  • What gets printed?

formal parameter

actual parameter


Java parameter passing5
Java parameter passing rectangles.

  • The value of the actual parameter gets copied to the formal parameter

    • This is called pass-by-value

    • C/C++ is also pass-by-value

    • Other languages have other parameter passing types

  • Any changes to the formal parameter are forgotten when the method returns

  • However, if the parameter is a reference to an object, that object can be modified

    • Similar to how the object a final reference points to can be modified


Subtleties
Subtleties rectangles.

  • 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?


Other mutators
Other mutators rectangles.

public 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;

}


Mutator usage

Sends a message to rectangles.

u's ColoredRectangle

to modify its height

attribute to 100

Sends a message to u's Colored-

Rectangle to modify its color

attribute to pink

Sends a message to v's Colored-

Rectangle to modify its x-axis

Sends a message to v's Colored-

position to 25

Rectangle to modify its window

attribute to display's JFrame

Sends a message to v's Colored-

Rectangle to modify its y-axis

position to 50

Mutator usage

ColoredRectangle u =

new

ColoredRectangle();

ColoredRectangle v =

new

ColoredRectangle();

u.setHeight(100);

u.setColor(Color.PINK);

v.setX(25);

v.setY(50);

new JFrame("Fun");

JFrame display =

v.setWindow(display);


Accessors

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

method definition

For method getWidth(), the return value is the value of the width

attribute for the ColoredRectangle associated with the invocation.

In invocation t.getWidth(), the return value is the value of the

instance variable width for the ColoredRectangle referenced by t

Accessors

  • Properties

    • Do not require parameters

    • Each accessor execution produces a return value

      • Return value is the value of the invocation

getWidth() {

public int

return

width;

}


Accessor usage

Invocation sends a message to the ColoredRectangle the

referenced by t to return the value of its width. To do so,

there is a temporary transfer of flow of control to getWidth()

Method getWidth() starts executing.

For this invocation, the object being

referenced is the object referenced by t

The return expression evaluates to 40 (the width

attribute of the ColoredRectangle object referenced by t )

Method completes by supplying its return value (40) to the invoking

statement. Also, invoking statement regains the flow of control. From

there variable w is initialized with the return value of the invocatio

Accessor usage

new

ColoredRectangle t =

ColoredRectangle();

int

w = t

.getWidth();

public

class

ColoredRectangle {

...

/

/

getWidth(): accessor

public int

getWidth

(

) {

return

width

;

}

...

}


Specific construction
Specific construction the

public 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 attributes

    JFrame display = new JFrame("Even more fun");

    display.setSize(400, 400);

    ColoredRectangle w = new ColoredRectangle(60, 80,

    20, 20, display, Color.YELLOW);


Specific construction1
Specific construction the

public 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


Seeing double
Seeing double the

import java.awt.*;

public class SeeingDouble {

public static void main(String[] args) {

ColoredRectangle r = new ColoredRectangle();

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

Scanner stdin = new Scanner (System.in);

stdin.nextLine();

r.paint();

r.setY(50);

r.setColor(Color.RED);

r.paint();

}

}




Casting
Casting the

  • We’ve seen casting before:

    • double d = (double) 3;

    • int x = (int) d;

  • Aside: duplicating an object

    • String s = “foo”;

    • String t = s.clone();

      • Causes an error: “inconvertible types”

      • (Causes another error, but we will ignore that one)

    • What caused this?


Casting take 2
Casting, take 2 the

  • .clone() returns an object of class Object (sic)

    • More confusion: You can also have an object of class Class

      • Thus, you can have an Object class and a Class object

      • Got it?

    • We know it’s a String (as it cloned a String)

    • Thus, we need to tell Java it’s a String via casting

  • Revised code:

    • String s = “foo”;

    • String t = (String) s.clone();

      • Still causes that “other” error, but we are still willfully ignoring it…


Casting take 3
Casting, take 3 the

  • That “other” error is because String does not have a .clone() method

    • Not all classes do!

    • We just haven’t seen any classes that do have .clone() yet

  • Check in the documentation if the object you want to copy has a .clone() method

  • A class that does: java.util.Vector

    • Vector s = new Vector();

    • Vector t = s.clone();

    • Vector u = (Vector) s.clone();

Causes the “inconvertible types” error


Casting take 4
Casting, take 4 the

  • What happens with the following code?

    • Vector v = new Vector();

    • String s = (String) v;

  • Java will encounter a compile-time error

    • “inconvertible types”

  • What happens with the following code?

    • Vector v = new Vector();

    • String s = (String) v.clone();

  • Java will encounter a RUN-time error

    • ClassCastException