Download presentation
Presentation is loading. Please wait.
Published byDella Bradford Modified over 9 years ago
1
1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield
2
2 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
3
3 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
4
4 First class – ColoredRectangle Purpose Represent a colored rectangle in a window Introduce the basics of object design and implementation
5
5 Background JFrame Principal Java class for representing a titled, bordered graphical window. Standard class Part of the swing library import javax.swing.* ;
6
6 Some Java Swing components
7
7 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);
8
// 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); }
9
9 An optical illusion
10
10 Another optical illusion
11
11 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
12
12 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
13
// 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 }
14
14 End of lecture on 7 February 2005
15
15 ColoredRectangle.java outline 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() { //... }
16
16 Instance variables and attributes Data field Java term for an object attribute Instance variable Another name for a data field Usually has private access Assists in information hiding by encapsulating the object’s attributes We’ll talk more about private later Default initialization Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null
17
public class ColoredRectangle { // 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); }
18
18 ColoredRectangle default constructor public class ColoredRectangle{ // instance variables to describe object attributes... // ColoredRectangle(): default constructor public ColoredRectangle() {... } } A constructor does not list its return type. A constructor always returns a reference to a new object of its class The name of a constructor always matches the name of its class
19
19 Quick survey I understand the purpose of a constructor I understand the purpose of a constructor a) Very well b) With some review, I’ll be good c) Not really d) Not at all
20
public class ColoredRectangle { // 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); }
21
21 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
22
r The value of a ColoredRectangle variable is a reference to a ColoredRectangle object + paint() : void ColorRectangle - width = 40 - height = 20 - x = 80 - y = 90 - window = - color = Color - color = -... + brighter() : Color +... String - text = "Box Fun" -... + length() : int +... + setVisible( boolean status) : void +... JFrame - width = 200 - height = 200 - title = -... ColoredRectangle r = new ColoredRectangle();
23
23 Quick survey I understood the memory diagram from the previous slide I understood the memory diagram from the previous slide a) Very well b) With some review, I’ll be good c) Not really d) Not at all
24
24 Computer bugs
25
25 Another possible Constructor 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); }
26
public class ColoredRectangle { // 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); }
27
27 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
28
28 Java coordinate system
29
29 Method invocation 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
30
30 Method invocation public class ColoredRectangle{ // instance variables to describe object attributes... // paint(): display the rectangle in its window publicvoid paint() { window.setVisible( true); Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }... } Instance variable window references the JFrame attribute of the object that caused the invocation. The values of these instance variables are also from the ColoredRectangle object Typo in book: p. 149 claims paint() is static; it is not
31
31 Quick survey I understood the ColoredRectangle class I understood the ColoredRectangle class a) Very well b) With some review, I’ll be good c) Not really d) Not at all
32
32 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
33
33 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
34
34 A mutator method Definition // setWidth(): width mutator public void setWidth(int w) { width = w; } Usage ColoredRectangle s = new ColoredRectangle(); s.setWidth(80); public void setWidth(intw) {... } Initial value of the formal parameter comes from the actual parameter Changes to the formal parameter do not affect the actual parameter Object to be manipulated is the one referenced by s
35
35 Mutator setWidth() evaluation ColoredRectangle s = new ColoredRectangle(); s.setWidth(80); publicclass ColoredRectangle {... // setWidth(): width mutator public void setWidth( int w) { width = w; }... } The invocation sends a message to the ColoredRectangle referenced by s to modify its width attribute. Method setWidth() sets the instance variable width of its ColoredRectangle. For this invocation of method setWidth(), w is initialized to 80 Method setWidth() is completed. Control is transferred back
36
36 Today’s demotivators
37
37 Java parameter passing The value is copied to the method Any changes to the parameter are forgotten when the method returns
38
38 Java parameter passing 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 y 5 x 5 y 7
39
39 Java parameter passing 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 yx “5"“7"
40
40 Java parameter passing 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(x.getWidth()); } What gets printed? formal parameter actual parameter yx width = 0width = 10
41
41 Java parameter passing 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 yx width = 0 width = 10
42
42 Java parameter passing 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
43
43 Quick survey I felt I understand Java parameter passing I felt I understand Java parameter passing a) Very well b) With some review, I’ll be good c) Not really d) Not at all
44
44 End of lecture on 9 February 2005
45
45 Damage Control
46
46 The main() method Consider a class with many methods: public class WhereToStart { public static void foo (int x) { //... } public static void bar () { //... } public static void main (String[] args) { //... } } Where does Java start executing the program? Always at the beginning of the main() method!
47
47 Variable scoping A variable is visible within the block it is declared in Called the “scope” of the variable public class Scoping { int z public static void foo (int x) { //... } public static void bar () { //... } public static void main (String[] args) { int y; //... } } This local variable is visible until the end of the main() method This instance variable is visible anywhere in the Scoping class This parameter is visible only in the foo() method
48
48 More on classes vs. objects
49
49 A new example: creating a Car class What properties does a car have in the real world? Color Position (x,y) Fuel in tank We will implement these properties in our Car class public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... }
50
50 Car’s instance variables public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... } + … Car - color - fuel - xpos - ypos
51
51 Instance variables and attributes Default initialization If the variable is within a method, Java does NOT initialize it If the variable is within a class, Java initializes it as follows: Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null + … Car - color = null - fuel = 0 - xpos = 0 - ypos = 0
52
52 Car behaviors or methods What can a car do? And what can you do to a car? Move it Change it’s x and y positions Change it’s color Fill it up with fuel For our computer simulation, what else do we want the Car class to do? Create a new Car Plot itself on the screen Each of these behaviors will be written as a method
53
53 Creating a new car To create a new Car, we call: Car car = new Car(); Notice this looks like a method You are calling a special method called a constructor A constructor is used to create (or construct) an object It sets the instance variables to initial values The constructor: public Car() { fuel = 1000; color = Color.BLUE; }
54
54 Constructors public Car() { fuel = 1000; color = Color.BLUE; } No return type! EXACT same name as class For now, all constructors are public
55
55 Our Car class so far public class Car { private Color color; private int xpos; private int ypos; private int fuel; public Car() { fuel = 1000; color = Color.BLUE; } } public class Car { private Color color = Color.BLUE; private int xpos; private int ypos; private int fuel = 1000; public Car() { }
56
56 Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } } Called the default constructor The default constructor has no parameters If you don’t include one, Java will SOMETIMES put one there automatically + Car() + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0
57
57 Another constructor Another constructor: public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } This constructor takes in four parameters The instance variables in the object are set to those parameters This is called a specific constructor An constructor you provide that takes in parameters is called a specific constructor
58
58 Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } } + Car() + Car (Color, int, int, int) + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0
59
59 Using our Car class Now we can use both our constructors: Car c1 = new Car(); Car c2 = new Car (Color.BLACK, 1, 2, 500); + Car() + Car (Color, int, int, int) + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0 + Car() + Car (Color, int, int, int) + … Car - color = Color.BLACK - fuel = 500 - xpos = 1 - ypos = 2 c1c2
60
60 Quick survey How much of a Star Wars fan are you? How much of a Star Wars fan are you? a) I already have my Episode 3 tickets b) I’ll see it in the theater c) I’ll rent it on DVD d) Is that like that Star Trek thing?
61
61 Star Wars Episode 3 Trailer
62
62 Star Wars Episode 3 Trailer That was a edited version That was a edited version –I changed the PG-rated trailer to a G-rated trailer The original one can be found at http://www.sequentialpictures.com/ The original one can be found at http://www.sequentialpictures.com/ –Or Google for “star wars parody”
63
63 So what does private mean? Consider the following code public class CarSimulation { public static void main (String[] args) { Car c = new Car(); System.out.println (c.fuel); } } Recall that fuel is a private instance variable in the Car class Private means that code outside the class CANNOT access the variable For either reading or writing Java will not compile the above code If fuel were public, the above code would work Note that it’s a different class!
64
64 So how do we get the fuel of a Car? Via accessor methods in the Car class: public int getFuel() { return fuel; } public Color getColor() { return color; } As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public int getYPos() { return ypos; } public int getXPos() { return xpos; }
65
65 So how do we set the fuel of a Car? Via mutator methods in the Car class: public void setFuel (int f) { fuel = f; } public void setColor (Color c) { color = c; } As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; }
66
66 Quick survey I vaguely understand the public/private stuff I vaguely understand the public/private stuff a) Very well b) With some review, I’ll be good c) Not really d) Not at all
67
67 Why use all this? These methods are called a get/set pair Used with private variables We’ll see why one uses these later on in the course Our Car so far: + Car() + Car (Color, int, int, int) + void setXPos (int x) + void setYPos (int y) + void setPos (int x, int y) + void setColor (Color c) + void setFuel (int f) + int getFuel() + int getXPos() + int getYPos() + Color getColor() + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0
68
68 Back to our specific constructor public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } } public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { setColor (c); setXPos (x); setYPos (y); setFuel (f); }
69
69 Back to our specific constructor Using the mutator methods (i.e. the ‘set’ methods) is the preferred way to modify instance variables in a constructor We’ll see why later
70
70 So what’s left to add to our Car class? What else we should add: A mutator that sets both the x and y positions at the same time A means to “use” the Car’s fuel A method to paint itself on the screen Let’s do the first: public void setPos (int x, int y) { setXPos (x); setYPos (y); } Notice that it calls the mutator methods
71
71 Using the Car’s fuel Whenever the Car moves, it should burn some of the fuel For each pixel it moves, it uses one unit of fuel We could make this more realistic, but this is simpler public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; } public void setXPos (int x) { fuel -= Math.abs (getXPos()-x); xpos = x; } public void setYPos (int y) { fuel -= Math.abs (getYPos()-y); ypos = y; }
72
72 Using the Car’s fuel Notice that to access the instance variables, the accessor methods are used Math.abs() gets the absolute value of the passed parameter public void setPos (int x, int y) { setXPos(x); setYPos(y); } public void setPos (int x, int y) { setXPos(x); setYPos(y); }
73
73 Just in time for Valentine’s Day Black Monday
74
74 Bittersweets: Dejected sayings I MISS MY EX I MISS MY EX PEAKED AT 17 PEAKED AT 17 MAIL ORDER MAIL ORDER TABLE FOR 1 TABLE FOR 1 I CRY ON Q I CRY ON Q U C MY BLOG? U C MY BLOG? REJECT PILE REJECT PILE PILLOW HUGGIN PILLOW HUGGIN ASYLUM BOUND ASYLUM BOUND DIGNITY FREE DIGNITY FREE PROG FAN PROG FAN STATIC CLING STATIC CLING WE HAD PLANS WE HAD PLANS XANADU 2NITE XANADU 2NITE SETTLE 4LESS SETTLE 4LESS NOT AGAIN NOT AGAIN
75
75 Bittersweets: Dysfunctional sayings RUMORS TRUE RUMORS TRUE PRENUP OKAY? PRENUP OKAY? HE CAN LISTEN HE CAN LISTEN GAME ON TV GAME ON TV CALL A 900# CALL A 900# P.S. I LUV ME P.S. I LUV ME DO MY DISHES DO MY DISHES UWATCH CMT UWATCH CMT PAROLE IS UP! PAROLE IS UP! BE MY YOKO BE MY YOKO U+ME=GRIEF U+ME=GRIEF I WANT HALF I WANT HALF RETURN 2 PIT RETURN 2 PIT NOT MY MOMMY NOT MY MOMMY BE MY PRISON BE MY PRISON C THAT DOOR? C THAT DOOR?
76
76 Drawing the Car The simple way to have the Car draw itself: public void paint (Graphics g) { g.setColor (color); g.fillRect (xpos-50, ypos-100, 100, 200); } This draws a single rectangle that is 100 by 200 pixels in size Lets use constants for the car’s height and width...
77
77 Drawing the Car A better version: private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); } This makes it easier to change the car size We could have made the car size instance variables and set them via mutators Lets add tires!
78
78 End of lecture on 14 February 2005
79
79 Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); } Don’t worry about this – just know that it draws four tires
80
80 What happens when the car runs out of fuel? We could do a number of things: Not allow the car to move anymore Print out a message saying, “fill me up!” We’ll color the car red We’ll insert the following code at the beginning of the paint() method: if ( fuel < 0 ) { color = Color.RED; } We haven’t seen if statements yet Basically, this says that if the fuel is less than zero, color the car red We’ll see if statements in chapter 5
81
81 Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { if ( fuel < 0 ) { color = Color.RED; } g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); }
82
82 Our car in action ...
83
83 Quick survey I understood about creating the Car class I understood about creating the Car class a) Very well b) With some review, I’ll be good c) Not really d) Not at all
84
84 Medicine Medicine Physics Physics Public Health Public Health Chemistry Chemistry Engineering Engineering Literature Literature Psychology Psychology Economics Economics Peace Peace Biology Biology The 2004 Ig Nobel Prizes "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
85
85 What I’m not expecting you to know yet… What the static keyword means And why the main() method is And why other methods are not Why you should always call the mutator methods, instead of setting the field directly Just know that it’s a good programming practice, and follow it We’ll see why next chapter Why instance variables are supposed to be private Just know that it’s a good programming practice, and follow it
86
86 What we’ve seen so far Two examples of creating a class ColoredRectangle Car Up next: another example Rational Represents rational numbers A rational number is any number that can be expressed as a fraction Both the numerator and denominator must be integers! Discussed in section 4.8 of the textbook
87
87 What properties should our Rational class have? The numerator (top part of the fraction) The denominator (bottom part of the fraction) Not much else…
88
88 What do we want our Rational class to do? Obviously, the ability to create new Rational objects Setting the numerator and denominator Getting the values of the numerator and denominator Perform basic operations with rational numbers: + - * / Ability to print to the screen
89
89 Our first take at our Rational class Our first take public class Rational { private int numerator; private int denominator; //... } This does not represent a valid Rational number! Why not? Java initializes instance variables to zero Both the numerator and denominator are thus set to zero 0/0 is not a valid number! + … Rational - numerator = 0- denominator = 0
90
90 Our next take at our Rational class Our next take public class Rational { private int numerator = 0; private int denominator = 1; //... } We’ve defined the attributes of our class Next up: the behaviors + … Rational - numerator = 0- denominator = 1
91
91 The default constructor Ready? public Rational() { } Yawn! Note that we could have initialized the instance variables here instead The default constructor is called that because, if you don’t specify ANY constructors, then Java includes one by default Default constructors do not take parameters + Rational() + … Rational - numerator = 0- denominator = 1
92
92 The specific constructor Called the specific constructor because it is one that the user specifies They take one or more parameters public Rational (int num, int denom) { setNumerator (num); setDenominator (denom); } Note that the specific constructor calls the mutator methods instead of setting the instance variables directly We’ll see why next chapter + Rational() + Rational (int num, int denom) + … Rational - numerator = 0- denominator = 1
93
93 Accessor methods Our two accessor methods: public int getNumerator () { return numerator; } public int getDenominator () { return denominator; } + Rational() + Rational (int num, int denom) + int getNumerator() + int getDemonimator() + … Rational - numerator = 0- denominator = 1
94
94 Mutator methods Our two mutator methods: public void setNumerator (int towhat) { numerator = towhat; } public void setDenominator (int towhat) { denominator = towhat; }
95
95 Rational addition How to do Rational addition: Our add() method: public Rational add (Rational other) { }
96
96 The this keyword + Rational () + Rational (int n, int d) + Rational add (Rational other) + … Rational - numerator = 1- denominator = 2 this + Rational () + Rational (int n, int d) + Rational add (other ) + … Rational - numerator = 1- denominator = 2 + Rational () + Rational (int n, int d) + Rational add (Rational other) + … Rational - numerator = 1- denominator = 3 + Rational () + Rational (int n, int d) + Rational add (Rational other) + … Rational - numerator = 5- denominator = 6 Returns:
97
97 The this keyword this is a reference to whatever object we are currently in Will not work in static methods We’ll see why later Note that the main() method is a static method While we’re at it, when defining a class, note that NONE of the methods were static
98
98 Today’s demotivators
99
99 Rational addition How to do Rational addition: Our add() method: public Rational add (Rational other) { int a = this.getNumerator(); int b = this.getDenominator(); int c = other.getNumerator(); int d = other.getDenominator(); return new Rational (a*d+b*c, b*d); }
100
100 Rational subtraction How to do Rational subtraction: Our subtract() method: public Rational subtract (Rational other) { int a = this.getNumerator(); int b = this.getDenominator(); int c = other.getNumerator(); int d = other.getDenominator(); return new Rational (a*d-b*c, b*d); }
101
101 Rational multiplication How to do Rational multiplication: Our multiply() method: public Rational multiply (Rational other) { int a = this.getNumerator(); int b = this.getDenominator(); int c = other.getNumerator(); int d = other.getDenominator(); return new Rational (a*c, b*d); }
102
102 Rational division How to do Rational division: Our divide() method: public Rational divide (Rational other) { int a = this.getNumerator(); int b = this.getDenominator(); int c = other.getNumerator(); int d = other.getDenominator(); return new Rational (a*d, b*c); }
103
103 Printing it to the screen If we try printing a Rational object to the screen: Rational r = new Rational (1,2); System.out.println (r); We get the following: Rational@82ba41 Ideally, we’d like something more informative printed to the screen The question is: how does Java know how to print a custom class to the screen?
104
104 The toString() method When an object is put into a print statement: Rational r = new Rational (1,2); System.out.println (r); Java will try to call the toString() method to covert the object to a String If the toString() method is not found, a default one is included Hence the Rational@82ba41 from the previous slide So let’s include our own toString() method
105
105 The toString() method Our toString() method is defined as follows: public String toString () { return getNumerator() + "/" + getDenominator(); } Note that the prototype must ALWAYS be defined as shown The prototype is the ‘public String toString()’
106
106 Printing it to the screen Now, when we try printing a Rational object to the screen: Rational r = new Rational (1,2); System.out.println (r); We get the following: 1/2 Which is what we wanted! Note that the following two lines are equivalent: System.out.println (r); System.out.println (r.toString());
107
107 Our full Rational class + Rational() + Rational (int num, int denom) + int getNumerator() + int getDemonimator() + void setNumerator (int num) + void setDenominator (int denom) + Rational add (Rational other) + Rational subtract (Rational other) + Rational multiply (Rational other) + Rational divide (Rational other) + String toString() Rational - numerator = 0- denominator = 1
108
108 Our Rational class in use, part 1 of 4 This code is in a main() method of a RationalDemo class First, we extract the values for our first Rational object: Scanner stdin = new Scanner(System.in); System.out.println(); // extract values for rationals r and s Rational r = new Rational(); System.out.print("Enter numerator of a rational number: "); int a = stdin.nextInt(); System.out.print("Enter denominator of a rational number: "); int b = stdin.nextInt(); r.setNumerator(a); r.setDenominator(b);
109
109 Our Rational class in use, part 2 of 4 Next, we extract the values for our second Rational object: Rational s = new Rational(); System.out.print("Enter numerator of a rational number: "); int c = stdin.nextInt(); System.out.print("Enter denominator of a rational number: “); int d = stdin.nextInt(); s.setNumerator(c); s.setDenominator(d); Notice that I didn’t create another Scanner object! Doing so would be bad I used the same one
110
110 Our Rational class in use, part 3 of 4 Next, we do the arithmetic: // operate on r and s Rational sum = r.add(s); Rational difference = r.subtract(s); Rational product = r.multiply(s); Rational quotient = r.divide(s);
111
111 Our Rational class in use, part 4 of 4 Lastly, we print the results // display operation results System.out.println("For r = " + r.toString() + " and s = " + s.toString()); System.out.println(" r + s = " + sum.toString()); System.out.println(" r - s = " + difference.toString()); System.out.println(" r * s = " + product.toString()); System.out.println(" r / s = " + quotient.toString()); System.out.println();
112
112 A demo of our Rational class ……
113
113 Other things we might want to add to our Rational class The ability to reduce the fraction So that 2/4 becomes 1/2 Not as easy as it sounds! More complicated arithmetic Such as exponents, etc. Invert Switches the numerator and denominator Negate Changes the rational number into its (additive) negation We won’t see any of that here
114
114 Quick survey I felt I understood the Rational class… I felt I understood the Rational class… a) Very well b) With some review, I’ll be good c) Not really d) Not at all
115
115 Quick survey I feel I could define my own class… I feel I could define my own class… a) Very well b) With some review, I’ll be good c) Not really d) Not at all
116
116 Quick survey I would like to see another example of creating a class (we probably will still do it, though)… I would like to see another example of creating a class (we probably will still do it, though)… a) Definitely! b) Sure, why not? c) Not really d) No more! I can’t take it anymore!!!!
117
117 Warn your grandparents! Historically, this class has been lethal to grandparents of students in the class Historically, this class has been lethal to grandparents of students in the class –More often grandmothers This happens most around test time This happens most around test time –Although occasionally around the times a big assignment is due –The lower your course average, the more likely it is to occur http://biology.ecsu.ctstateu.edu/People/ConnRev.html http://biology.ecsu.ctstateu.edu/People/ConnRev.html http://biology.ecsu.ctstateu.edu/People/ConnRev.html
118
118 Java parameter passing The value is copied from the actual parameter to the formal parameter Any changes to the formal parameter are forgotten when the method returns
119
119 Java parameter passing 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? 5 formal parameter actual parameter y 5 x 5 y 7
120
120 Java parameter passing Consider the following code: static void foobar (double y) { y = 7.0; } public static void main (String[] args) { double x = 5.0; foobar (x); System.out.println(x); } What gets printed? 5.0 formal parameter actual parameter y 5.0 x y 7.0
121
121 Java parameter passing 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? 5 formal parameter actual parameter yx “5"“7"
122
122 Java parameter passing 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(x.getWidth()); } What gets printed? 10 formal parameter actual parameter yx width = 0width = 10
123
123 End of lecture on 16 February 2005
124
124 Java parameter passing 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? 0 formal parameter actual parameter yx width = 0 width = 10
125
125 Java parameter passing 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
126
126 Quick survey I felt I understand Java parameter passing I felt I understand Java parameter passing a) Very well b) With some review, I’ll be good c) Not really d) Not at all
127
127 Casting 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?
128
128 Casting, take 2 .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…
129
129 Casting, take 3 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
130
130 Casting, take 4 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
131
131 Quick survey I felt I understood the material in this slide set… I felt I understood the material in this slide set… a) Very well b) With some review, I’ll be good c) Not really d) Not at all
132
132 Quick survey The pace of the lecture for this slide set was… The pace of the lecture for this slide set was… a) Fast b) About right c) A little slow d) Too slow
133
133 Quick survey How interesting was the material in this slide set? Be honest! How interesting was the material in this slide set? Be honest! a) Wow! That was SOOOOOOO cool! b) Somewhat interesting c) Rather boring d) Zzzzzzzzzzz
134
134 Today’s demotivators
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.