Classes CS 101 E Chapter 4 Aaron Bloomfield

  • Slides: 53
Download presentation
Classes CS 101 -E Chapter 4 Aaron Bloomfield 1

Classes CS 101 -E Chapter 4 Aaron Bloomfield 1

Announcements o o o o HWs are being renumbered n J 1, J 2,

Announcements o o o o HWs are being renumbered n J 1, J 2, etc. , for Java programming assignments n C 1, C 2, etc. , for Code. Lab assignments n HW 1 = J 1, HW 2 = C 1, HW 3 = C 2, etc. HWs J 2 and J 3 assigned this Wednesday (6 Oct) n J 2 due next Thursday (14 Oct) n J 3 due following Thursday (21 Oct) HW J 4 will be assigned 18 Oct, and due 29 Oct Some Code. Lab HWs in there as well Second midterm on 27 Oct No labs this Sunday n Can go to another lab with permission Lab quiz grades will be entered by the end of this week 2

Preparation o o Scene so far has been background material and experience n Computing

Preparation o o Scene so far has been background material and experience n Computing systems and problem solving n Variables n Types n Input and output n Expressions n Assignments n Objects n Standard classes and methods Now: Experience what Java is really about n Design and implement objects representing information and physical world objects 3

Object-oriented programming o o o Basis n Create and manipulate objects with attributes behaviors

Object-oriented programming o o o Basis n Create and manipulate objects with attributes behaviors that the programmer can specify and Mechanism n Classes Benefits n An information type is design and implemented once o Reused as needed n No need reanalysis and re-justification of the representation 4

First class – Colored. Rectangle o Purpose n Represent a colored rectangle in a

First class – Colored. Rectangle o Purpose n Represent a colored rectangle in a window n Introduce the basics of object design and implementation 5

Background o JFrame n Principal Java class for representing a titled, bordered graphical window.

Background o JFrame n Principal Java class for representing a titled, bordered graphical window. n Standard class o Part of the swing library import javax. swing. * ; 6

Some Java Swing components 7

Some Java Swing components 7

Example o Consider JFrame w 1 = new JFrame("Bigger"); JFrame w 2 = new

Example o Consider JFrame w 1 = new JFrame("Bigger"); JFrame w 2 = new JFrame("Smaller"); w 1. set. Size(200, 125); w 2. set. Size(150, 100); w 1. set. Visible(true); w 2. set. Visible(true); 8

// Purpose: Displays two different windows. import javax. swing. *; public class Two. Windows

// Purpose: Displays two different windows. import javax. swing. *; public class Two. Windows { // main(): application entry point public static void main (String[] args) { JFrame w 1 = new JFrame("Bigger"); JFrame w 2 = new JFrame("Smaller"); w 1. set. Size(200, 125); w 2. set. Size(150, 100); w 1. set. Visible(true); w 2. set. Visible(true); } } 9

Class Colored. Rectangle – initial version o Purpose n Support the display of square

Class Colored. Rectangle – initial version o Purpose n Support the display of square window containing a blue filled-in rectangle o Window has side length of 200 pixels o Rectangle is 40 pixels wide and 20 pixels high o Upper left hand corner of rectangle is at (80, 90) n Limitations are temporary o Remember BMI. java preceded BMICalculator. java o Lots of concepts to introduce 10

Colored. Rectangle in action o Consider Colored. Rectangle r 1 = new Colored. Rectangle();

Colored. Rectangle in action o Consider Colored. Rectangle r 1 = new Colored. Rectangle(); Colored. Rectangle r 2 = new Colored. Rectangle(); System. out. println("Enter when ready"); Scanner stdin = new Scanner (System. in); stdin. next. Line(); r 1. paint(); // draw the window associated with r 1 r 2. paint(); // draw the window associated with r 2 11

// Purpose: Create two windows containing colored rectangles. import java. util. *; public class

// Purpose: Create two windows containing colored rectangles. import java. util. *; public class Box. Fun { //main(): application entry point public static void main (String[] args) { Colored. Rectangle r 1 = new Colored. Rectangle(); Colored. Rectangle r 2 = new Colored. Rectangle(); System. out. println("Enter when ready"); Scanner stdin = new Scanner (System. in); stdin. next. Line(); r 1. paint(); r 2. paint(); // draw the window associated with r 1 // draw the window associated with r 2 } } 12

Colored. Rectangle. java outline import javax. swing. *; import java. awt. *; public class

Colored. Rectangle. java outline import javax. swing. *; import java. awt. *; public class Colored. Rectangle { // instance variables for holding object attributes private private int width; int height; int x; int y; JFrame window; Color color; // Colored. Rectangle(): default constructor public Colored. Rectangle() { } //. . . // paint(): display the rectangle in its window public void paint() { } } //. . . 13

Instance variables and attributes o o Data field n Java term for an object

Instance variables and attributes o o Data field n Java term for an object attribute Instance variable n Symbolic name for a data field n n Usually has private access o Assists in information hiding by encapsulating the object’s attributes Default initialization o Numeric instance variables initialized to 0 o Logical instance variables initialized to false o Object instance variables initialized to null 14

public class Colored. Rectangle { // instance variables for holding object attributes private int

public class Colored. Rectangle { // instance variables for holding object attributes private int width; private int height; private JFrame window; private int x; private int y; private Color color; // Colored. Rectangle(): default constructor public Colored. Rectangle() { window = new JFrame("Box Fun"); window. set. Size(200, 200); width = 40; x = 80; height = 20; y = 90; color = Color. BLUE; window. set. Visible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window. get. Graphics(); g. set. Color(color); g. fill. Rect(x, y, width, height); } } 15

Colored. Rectangle default constructor 16

Colored. Rectangle default constructor 16

public class Colored. Rectangle { // instance variables for holding object attributes private int

public class Colored. Rectangle { // instance variables for holding object attributes private int width; private int height; private JFrame window; private int x; private int y; private Color color; // Colored. Rectangle(): default constructor public Colored. Rectangle() { window = new JFrame("Box Fun"); window. set. Size(200, 200); width = 40; x = 80; height = 20; y = 90; color = Color. BLUE; window. set. Visible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window. get. Graphics(); g. set. Color(color); g. fill. Rect(x, y, width, height); } } 17

Color constants o o o o Color. BLACK Color. BLUE Color. CYAN Color. DARK_GRAY

Color constants o o o o Color. BLACK Color. BLUE Color. CYAN Color. DARK_GRAY Color. GREEN Color. LIGHT_GRAY Color. MAGENTA Color. ORANGE Color. PINK Color. RED Color. WHITE Color. YELLOW 18

r Colored. Rectangle r = new Colored. Rectangle(); Color. Rectangle The value of a

r Colored. Rectangle r = new Colored. Rectangle(); Color. Rectangle The value of a Colored. Rectangle variable is a reference to a Colored. Rectangle object - width = 40 - height = 20 - x = 80 - y = 90 - window = - color = + paint() : String void + brighter() : Color +. . . = "Box Fun" + length() +. . . Color - color = -. . . - text -. . . : int JFrame - width = 200 - height = 200 - title = -. . . + set. Visible( +. . . boolean status) : void 19

Another possible Constructor public class Colored. Rectangle { // instance variables for holding object

Another possible Constructor public class Colored. Rectangle { // instance variables for holding object attributes private int width = 40; private int height = 80; private JFrame window; private int x = 80; private int y = 90; private Color color = Color. BLUE; // Colored. Rectangle(): default constructor public Colored. Rectangle() { window = new JFrame("Box Fun"); window. set. Size(200, 200); window. set. Visible(true); } 20

public class Colored. Rectangle { // instance variables for holding object attributes private int

public class Colored. Rectangle { // instance variables for holding object attributes private int width; private int height; private JFrame window; private int x; private int y; private Color color; // Colored. Rectangle(): default constructor public Colored. Rectangle() { window = new JFrame("Box Fun"); window. set. Size(200, 200); width = 40; x = 80; height = 20; y = 90; color = Color. BLUE; window. set. Visible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window. get. Graphics(); g. set. Color(color); g. fill. Rect(x, y, width, height); } } 21

Graphical context o Graphics n Defined in java. awt. Graphics n Represents the information

Graphical context o Graphics n Defined in java. awt. Graphics n Represents the information for a rendering request o Color o Component o Font o … n Provides methods n Text drawing o Line drawing o Shape drawing n Rectangles n Ovals n Polygons 22

Java coordinate system 23

Java coordinate system 23

Method invocation o o Consider r 1. paint(); // display window associated with r

Method invocation o o Consider r 1. paint(); // display window associated with r 1 r 2. paint(); // display window associated with r 2 Observe n When an instance method is being executed, the attributes of the object associated with the invocation are accessed and manipulated n Important that you understand what object is being manipulated 24

Method invocation public class Colored. Rectangle { // instance variables to describe object attributes.

Method invocation public class Colored. Rectangle { // instance variables to describe object attributes. . . // paint(): display the rectangle in its window public void paint() { window. set. Visible( true ); Graphics g = window. get. Graphics(); g. set. Color(color); g. fill. Rect(x, y, width, height); }. . . } The values of these instance variables are also from the Colored. Rectangle object Instance variable window references the JFrame attribute of the object that caused the invocation. Typo in book: p. 149 claims paint() is static; it’s not 25

The Ig Nobel Prizes o o o o Medicine Physics Public Health Chemistry Engineering

The Ig Nobel Prizes o o o o Medicine Physics Public Health Chemistry Engineering Literature Psychology o Economics Peace o Biology o "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 26 communicate by farting

Wednesday, 6 October, 2004 o Computing grades so far HW J 2 assigned today,

Wednesday, 6 October, 2004 o Computing grades so far HW J 2 assigned today, due next Wednesday Lab this week! Must be done by Sunday at 8: 30 Sunday labs are cancelled due to fall break n 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 o HISTORICALLY, the grade range has been: o o o n A: 90+, B: 80 -89, C: 60 -79, D/F: <60 27

Improving Colored. Rectangle o Analysis n A Colored. Rectangle object should o Be able

Improving Colored. Rectangle o Analysis n A Colored. Rectangle object should o Be able to have any color o Be positionable anywhere within its window o Have no restrictions on its width and height o Accessible attributes o Updateable attributes 28

Improving Colored. Rectangle o Additional constructions and behaviors n Specific construction o Construct a

Improving Colored. Rectangle o Additional constructions and behaviors n Specific construction o Construct a rectangle representation using supplied values for its attributes n n Accessors o Supply the values of the attributes o Individual methods for providing the width, height, xcoordinate position, y-coordinate position, color, or window of the associated rectangle Mutators o Manage requests for changing attributes o Ensure objects always have sensible values o Individual methods for setting the width, height, xcoordinate position, y-coordinate position, color, or 29 window of the associated rectangle to a given value

A mutator method o o Definition // set. Width(): width mutator public void set.

A mutator method o o Definition // set. Width(): width mutator public void set. Width(int w) { width = w; } Usage Colored. Rectangle s = new Colored. Rectangle(); s. set. Width(80); Initial value of the formal parameter comes from the actual parameter Object to be manipulated is the one referenced by s public void set. Width ( int. . . } w) { Changes to the formal parameter 30 do not affect the actual parameter

Mutator set. Width() evaluation Colored. Rectangle s = new Colored. Rectangle(); s. set. Width(80);

Mutator set. Width() evaluation Colored. Rectangle s = new Colored. Rectangle(); s. set. Width(80); The invocation sends a message to the Colored. Rectangle referenced by s to modify its width attribute. To do so, there is a temporary transfer of flow of control to set. Width(). The value of the actual parameter is 80 public class Colored. Rectangle {. . . / / set. Width(): width mutator public void set. Width ( int w) { width = w; } . . . } For this invocation of method set. Width(), w is initialized to 80. The object being referenced within the method body is the object referenced by s Method set. Width() sets the instance variable width of its Colored. Rectangle. For this invocation, width is set to 80 and the Colored. Rectangle is the one referenced by s Method set. Width() is completed. Control is transferred back to 31 the statement that invoked set. Width()

A bit of humor… 32

A bit of humor… 32

Java parameter passing o o The value is copied to the method Any changes

Java parameter passing o o The value is copied to the method Any changes to the parameter are forgotten when the method returns 33

Java parameter passing o Consider the following code: static void foobar (int y) {

Java parameter passing o Consider the following code: static void foobar (int y) { y = 7; } formal parameter public static void main (String[] args) { int x = 5; actual parameter foobar (x); System. out. println(x); } o What gets printed? 34

Java parameter passing o Consider the following code: static void foobar (String y) {

Java parameter passing o Consider the following code: static void foobar (String y) { y = “ 7”; } formal parameter public static void main (String[] args) { String x = “ 5”; actual parameter foobar (x); System. out. println(x); } o What gets printed? 35

Java parameter passing o Consider the following code: static void foobar (Colored. Rectangle y)

Java parameter passing o Consider the following code: static void foobar (Colored. Rectangle y) { y. set. Width (10); formal parameter } public static void main (String[] args) { Colored. Rectangle x = new Colored. Rectangle(); foobar (x); actual parameter System. out. println(y. get. Width()); } o What gets printed? 36

Java parameter passing o Consider the following code: static void foobar (Colored. Rectangle y)

Java parameter passing o Consider the following code: static void foobar (Colored. Rectangle y) { y = new Colored. Rectangle(); y. set. Width (10); formal parameter } public static void main (String[] args) { Colored. Rectangle x = new Colored. Rectangle(); actual parameter foobar (x); System. out. println(y. get. Width()); } o What gets printed? 37

Java parameter passing o o o The value of the actual parameter gets copied

Java parameter passing o o o The value of the actual parameter gets copied to the formal parameter n This is called pass-by-value n C/C++ is also pass-by-value n 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 n Similar to how the object a final reference points to can be modified 38

Subtleties o o Consider Colored. Rectangle r = new Colored. Rectangle(); r. paint(); r.

Subtleties o o Consider Colored. Rectangle r = new Colored. Rectangle(); r. paint(); r. set. Width(80); r. paint(); What is the width is the rectangle on the screen after the mutator executes? 39

Other mutators public void set. Height(int h) { height = h; } public void

Other mutators public void set. Height(int h) { height = h; } public void set. X(int ulx) { x = ulx; } public void set. Y(int uly) { y = uly; } public void set. Window(JFrame f) { window = f; } public void set. Color(Color c) { color = c; } 40

41

41

Mutator usage Colored. Rectangle u = new Colored. Rectangle(); Colored. Rectangle v = new

Mutator usage Colored. Rectangle u = new Colored. Rectangle(); Colored. Rectangle v = new Colored. Rectangle(); u. set. Height(100); u. set. Color(Color. PINK); v. set. X(25); v. set. Y(50); JFrame display = new JFrame("Fun"); v. set. Window(display); Sends a message to v's Colored. Rectangle to modify its window attribute to display's JFrame Sends a message to u's Colored. Rectangle 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 position to 25 Sends a message to v's Colored. Rectangle to modify its y-axis position to 50 42

Accessors o Properties n Do not require parameters n Each accessor execution produces a

Accessors o Properties n Do not require parameters n Each accessor execution produces a return value o Return value is the value of the invocation The method return type precedes the name of the method in the method definition public int get. Width() { return width; } For method get. Width(), the return value is the value of the width attribute for the Colored. Rectangle associated with the invocation. In invocation t. get. Width(), the return value is the value of the instance variable width for the Colored. Rectangle referenced by t 43

Accessor usage Colored. Rectangle t = new Colored. Rectangle(); int w = t. get.

Accessor usage Colored. Rectangle t = new Colored. Rectangle(); int w = t. get. Width(); Invocation sends a message to the Colored. Rectangle referenced by t to return the value of its width. To do so, there is a temporary transfer of flow of control to get. Width() public class Colored. Rectangle {. . . Method get. Width() starts executing. / / get. Width(): accessor For this invocation, the object being public int get. Width ( ) { referenced is the object referenced by t return width ; } The return expression evaluates to 40 (the width attribute of the Colored. Rectangle 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 44 there variable w is initialized with the return value of the invocatio

Specific construction public Colored. Rectangle(int w, int h, int ulx, int uly, JFrame f,

Specific construction public Colored. Rectangle(int w, int h, int ulx, int uly, JFrame f, Color c) { set. Width(w); set. Height(h); set. X(ulx); set. Y(uly); set. Window(f); set. Color(c); } o Requires values for each of the attributes JFrame display = new JFrame("Even more fun"); display. set. Size(400, 400); Colored. Rectangle w = new Colored. Rectangle(60, 80, 20, display, Color. YELLOW); 45

Specific construction public Colored. Rectangle(int w, int h, int ulx, int uly, JFrame f,

Specific construction public Colored. Rectangle(int w, int h, int ulx, int uly, JFrame f, Color c) { set. Width(w); set. Height(h); set. X(ulx); set. Y(uly); set. Window(f); set. Color(c); } o Advantages to using mutators n Readability n Less error prone n Facilitates enhancements through localization 46

Seeing double import java. awt. *; public class Seeing. Double { public static void

Seeing double import java. awt. *; public class Seeing. Double { public static void main(String[] args) { Colored. Rectangle r = new Colored. Rectangle(); System. out. println("Enter when ready"); Scanner stdin = new Scanner (System. in); stdin. next. Line(); r. paint(); r. set. Y(50); r. set. Color(Color. RED); r. paint(); } } 47

Seeing double 48

Seeing double 48

An optical illusion 49

An optical illusion 49

Casting o o We’ve seen casting before: n double d = (double) 3; n

Casting o o We’ve seen casting before: n double d = (double) 3; n int x = (int) d; Aside: duplicating an object n String s = “foo”; n String t = s. clone(); o Causes an error: “inconvertible types” o (Causes another error, but we will ignore that one) n What caused this? 50

Casting, take 2 o . clone() returns an object of class Object (sic) n

Casting, take 2 o . clone() returns an object of class Object (sic) n n n o More confusion: You can also have an object of class Class o Thus, you can have an Object class and a Class object o 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: n String s = “foo”; n String t = (String) s. clone(); o Still causes that “other” error, but we are still willfully 51 ignoring it…

Casting, take 3 o o o That “other” error is because String does not

Casting, take 3 o o o That “other” error is because String does not have a. clone() method n Not all classes do! n 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 n Vector s = new Vector(); n Vector t = s. clone(); n Vector u = (Vector) s. clone(); Causes the “inconvertible types” error 52

Casting, take 4 o o What happens with the following code? n Vector v

Casting, take 4 o o What happens with the following code? n Vector v = new Vector(); n String s = (String) v; Java will encounter a compile-time error n “inconvertible types” What happens with the following code? n Vector v = new Vector(); n String s = (String) v. clone(); Java will encounter a RUN-time error n Class. Cast. Exception 53