1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield.

130
1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield

Transcript of 1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield.

  • ClassesChapter 4Spring 2005CS 101Aaron Bloomfield

  • PreparationScene so far has been background material and experienceComputing systems and problem solvingVariablesTypesInput and outputExpressions AssignmentsObjectsStandard classes and methods

    Now: Experience what Java is really aboutDesign and implement objects representing information and physical world objects

  • Object-oriented programmingBasisCreate and manipulate objects with attributes and behaviors that the programmer can specify

    MechanismClasses

    BenefitsAn information type is design and implemented onceReused as neededNo need reanalysis and re-justification of the representation

  • First class ColoredRectangle PurposeRepresent a colored rectangle in a windowIntroduce the basics of object design and implementation

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

    Standard classPart of the swing library

    import javax.swing.* ;

  • Some Java Swing components

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

  • // Purpose: Displays two different windows.

    import javax.swing.*;

    public class TwoWindows {// main(): application entry pointpublic 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);}}

  • An optical illusion

  • Another optical illusion

  • Class ColoredRectangle initial versionPurposeSupport the display of square window containing a blue filled-in rectangleWindow has side length of 200 pixelsRectangle is 40 pixels wide and 20 pixels highUpper left hand corner of rectangle is at (80, 90)

    Limitations are temporaryRemember BMI.java preceded BMICalculator.javaLots of concepts to introduce

  • ColoredRectangle in actionConsiderColoredRectangle 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 r1r2.paint(); // draw the window associated with r2ConsiderColoredRectangle 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 r1r2.paint(); // draw the window associated with r2ConsiderColoredRectangle 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 r1r2.paint(); // draw the window associated with r2ConsiderColoredRectangle 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 r1r2.paint(); // draw the window associated with r2

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

    import java.util.*;

    public class BoxFun {

    //main(): application entry pointpublic 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 r1r2.paint(); // draw the window associated with r2

    }}

  • End of lecture on 7 February 2005

  • ColoredRectangle.java outlineimport javax.swing.*;import java.awt.*;

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

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

  • Instance variables and attributesData fieldJava term for an object attribute

    Instance variableAnother name for a data field

    Usually has private accessAssists in information hiding by encapsulating the objects attributesWell talk more about private later

    Default initializationNumeric instance variables initialized to 0Logical instance variables initialized to falseObject instance variables initialized to null

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

    // ColoredRectangle(): default constructorpublic ColoredRectangle() {window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20;y = 90;color = Color.BLUE;window.setVisible(true);}

    // paint(): display the rectangle in its windowpublic void paint() {Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);}}

  • ColoredRectangle default constructor

  • Quick surveyI understand the purpose of a constructorVery wellWith some review, Ill be goodNot reallyNot at all

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

    // ColoredRectangle(): default constructorpublic ColoredRectangle() {window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20;y = 90;color = Color.BLUE;window.setVisible(true);}

    // paint(): display the rectangle in its windowpublic void paint() {Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);}}

  • Color constantsColor.BLACKColor.BLUE Color.CYAN Color.DARK_GRAY Color.GRAY Color.GREENColor.LIGHT_GRAYColor.MAGENTAColor.ORANGEColor.PINK Color.RED Color.WHITE Color.YELLOW

  • r ColoredRectangle r = new ColoredRectangle();

  • Quick surveyI understood the memory diagram from the previous slideVery wellWith some review, Ill be goodNot reallyNot at all

  • Computer bugs

  • Another possible Constructorpublic class ColoredRectangle {// instance variables for holding object attributesprivate 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 constructorpublic ColoredRectangle() {window = new JFrame("Box Fun");window.setSize(200, 200);window.setVisible(true);}

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

    // ColoredRectangle(): default constructorpublic ColoredRectangle() {window = new JFrame("Box Fun");window.setSize(200, 200);width = 40; x = 80;height = 20;y = 90;color = Color.BLUE;window.setVisible(true);}

    // paint(): display the rectangle in its windowpublic void paint() {Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);}}

  • Graphical contextGraphicsDefined in java.awt.GraphicsRepresents the information for a rendering requestColorComponentFontProvides methodsText drawingLine drawingShape drawingRectanglesOvalsPolygons

  • Java coordinate system

  • Method invocationConsiderr1.paint(); // display window associated with r1r2.paint(); // display window associated with r2

    ObserveWhen 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 invocationpublic class ColoredRectangle {// instance variables to describe object attributes...// paint(): display the rectangle in its windowpublic void paint() {window.setVisible(true);Graphics g = window.getGraphics();g.setColor(color);g.fillRect(x, y, width, height);}...}Typo in book: p. 149 claims paint() is static; it is not

  • Quick surveyI understood the ColoredRectangle classVery wellWith some review, Ill be goodNot reallyNot at all

  • Improving ColoredRectangleAnalysisA ColoredRectangle object shouldBe able to have any colorBe positionable anywhere within its windowHave no restrictions on its width and heightAccessible attributesUpdateable attributes

  • Improving ColoredRectangleAdditional constructions and behaviorsSpecific constructionConstruct a rectangle representation using supplied values for its attributes

    AccessorsSupply the values of the attributesIndividual methods for providing the width, height, x-coordinate position, y-coordinate position, color, or window of the associated rectangle

    MutatorsManage requests for changing attributesEnsure objects always have sensible valuesIndividual 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 methodDefinition// setWidth(): width mutatorpublic void setWidth(int w) {width = w;}UsageColoredRectangle s = new ColoredRectangle();s.setWidth(80);

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

  • Todays demotivators

  • Java parameter passingThe value is copied to the method

    Any changes to the parameter are forgotten when the method returns

  • Java parameter passingConsider 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 parameteractual parameter

  • Java parameter passingConsider 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 parameteractual parameter

  • Java parameter passingConsider 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 parameteractual parameter

  • Java parameter passingConsider 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 parameteractual parameter

  • Java parameter passingThe value of the actual parameter gets copied to the formal parameterThis is called pass-by-valueC/C++ is also pass-by-valueOther 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 modifiedSimilar to how the object a final reference points to can be modified

  • Quick surveyI felt I understand Java parameter passingVery wellWith some review, Ill be goodNot reallyNot at all

  • End of lecture on 9 February 2005

  • Damage Control

  • The main() methodConsider 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!

  • Variable scopingA variable is visible within the block it is declared inCalled 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() methodThis instance variable is visible anywhere in the Scoping classThis parameter is visible only in the foo() method

  • More on classes vs. objects

  • A new example: creating a Car classWhat properties does a car have in the real world?ColorPosition (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;

    //...}

  • Cars instance variablespublic class Car { private Color color; private int xpos; private int ypos; private int fuel;

    //...}

  • Instance variables and attributesDefault 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 0Logical instance variables initialized to falseObject instance variables initialized to null

  • Car behaviors or methodsWhat can a car do? And what can you do to a car?Move itChange its x and y positionsChange its colorFill it up with fuel

    For our computer simulation, what else do we want the Car class to do?Create a new CarPlot itself on the screen

    Each of these behaviors will be written as a method

  • Creating a new carTo create a new Car, we call:

    Car car = new Car();

    Notice this looks like a methodYou are calling a special method called a constructorA constructor is used to create (or construct) an objectIt sets the instance variables to initial values

    The constructor:

    public Car() {fuel = 1000;color = Color.BLUE;}

  • Constructors

    public Car() {fuel = 1000;color = Color.BLUE;}

    No return type!EXACT same name as classFor now, all constructors are public

  • Our Car class so farpublic 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() { }}

  • Our Car class so farpublic class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000;

    public Car() { }}

    Called the default constructorThe default constructor has no parametersIf you dont include one, Java will SOMETIMES put one there automatically

  • Another constructorAnother constructor:

    public Car (Color c, int x, int y, int f) {color = c;xpos = x;ypos = y;fuel = f; }

    This constructor takes in four parametersThe instance variables in the object are set to those parametersThis is called a specific constructorAn constructor you provide that takes in parameters is called a specific constructor

  • Our Car class so farpublic 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; }

    }

  • Using our Car classNow we can use both our constructors:

    Car c1 = new Car();Car c2 = new Car (Color.BLACK, 1, 2, 500);

  • Quick surveyHow much of a Star Wars fan are you?I already have my Episode 3 ticketsIll see it in the theaterIll rent it on DVDIs that like that Star Trek thing?

  • Star Wars Episode 3 Trailer

  • Star Wars Episode 3 TrailerThat was a edited versionI changed the PG-rated trailer to a G-rated trailer

    The original one can be found at http://www.sequentialpictures.com/Or Google for star wars parody

  • 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 classPrivate means that code outside the class CANNOT access the variableFor either reading or writingJava will not compile the above codeIf fuel were public, the above code would workNote that its a different class!

  • 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 variablesAs the methods are public, anybody can call thempublic int getYPos() { return ypos;}

    public int getXPos() {return xpos;}

  • 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 variablesAs the methods are public, anybody can call thempublic void setXPos (int x) { xpos = x;}

    public void setYPos (int y) { ypos = y;}

  • Quick surveyI vaguely understand the public/private stuffVery wellWith some review, Ill be goodNot reallyNot at all

  • Why use all this?These methods are called a get/set pairUsed with private variables

    Well see why one uses these later on in the course

    Our Car so far:

  • Back to our specific constructorpublic 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); }}

  • Back to our specific constructorUsing the mutator methods (i.e. the set methods) is the preferred way to modify instance variables in a constructorWell see why later

  • So whats 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 timeA means to use the Cars fuelA method to paint itself on the screen

    Lets do the first:

    public void setPos (int x, int y) {setXPos (x);setYPos (y); }

    Notice that it calls the mutator methods

  • Using the Cars fuelWhenever the Car moves, it should burn some of the fuelFor each pixel it moves, it uses one unit of fuelWe 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;}

  • Using the Cars fuel

    Notice that to access the instance variables, the accessor methods are usedMath.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);}

  • Just in time for Valentines Day Black Monday

  • Bittersweets: Dejected sayingsI MISS MY EXPEAKED AT 17MAIL ORDERTABLE FOR 1I CRY ON QU C MY BLOG?REJECT PILEPILLOW HUGGINASYLUM BOUNDDIGNITY FREEPROG FANSTATIC CLINGWE HAD PLANSXANADU 2NITESETTLE 4LESSNOT AGAIN

  • Bittersweets: Dysfunctional sayingsRUMORS TRUEPRENUP OKAY?HE CAN LISTENGAME ON TVCALL A 900#P.S. I LUV MEDO MY DISHESUWATCH CMT PAROLE IS UP!BE MY YOKOU+ME=GRIEFI WANT HALFRETURN 2 PITNOT MY MOMMYBE MY PRISONC THAT DOOR?

  • Drawing the CarThe 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 cars height and width...

  • Drawing the CarA 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 sizeWe could have made the car size instance variables and set them via mutators

    Lets add tires!

  • End of lecture on 14 February 2005

  • Drawing the Carprivate 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);}Dont worry about this just know that it draws four tires

  • What happens when the car runs out of fuel?We could do a number of things:Not allow the car to move anymorePrint out a message saying, fill me up!Well color the car red

    Well insert the following code at the beginning of the paint() method:

    if ( fuel < 0 ) { color = Color.RED;}

    We havent seen if statements yetBasically, this says that if the fuel is less than zero, color the car redWell see if statements in chapter 5

  • Drawing the Carprivate 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);}

  • Our car in action...

  • Quick surveyI understood about creating the Car classVery wellWith some review, Ill be goodNot reallyNot at all

  • The 2004 Ig Nobel PrizesMedicinePhysicsPublic Health ChemistryEngineeringLiteraturePsychology EconomicsPeace Biology"The Effect of Country Music on Suicide.For explaining the dynamics of hula-hoopingInvestigating the scientific validity of the Five-Second RuleThe Coca-Cola Company of Great BritainFor the patent of the comboverThe American Nudist Research LibraryIts easy to overlook things even a man in a gorilla suit.The Vatican, for outsourcing prayers to IndiaThe invention of karaoke, thereby providing an entirely new way for people to learn to tolerate each otherFor showing that herrings apparently communicate by farting

  • What Im not expecting you to know yet

    What the static keyword meansAnd why the main() method isAnd why other methods are not

    Why you should always call the mutator methods, instead of setting the field directlyJust know that its a good programming practice, and follow itWell see why next chapter

    Why instance variables are supposed to be privateJust know that its a good programming practice, and follow it

  • What weve seen so farTwo examples of creating a classColoredRectangleCar

    Up next: another exampleRationalRepresents rational numbersA rational number is any number that can be expressed as a fractionBoth the numerator and denominator must be integers!Discussed in section 4.8 of the textbook

  • What properties should our Rational class have?

    The numerator (top part of the fraction)

    The denominator (bottom part of the fraction)

    Not much else

  • 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

  • Our first take at our Rational classOur 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 zeroBoth the numerator and denominator are thus set to zero0/0 is not a valid number!

  • Our next take at our Rational classOur next take

    public class Rational {private int numerator = 0;private int denominator = 1; //...}

    Weve defined the attributes of our class

    Next up: the behaviors

  • The default constructorReady?

    public Rational() {}

    Yawn!

    Note that we could have initialized the instance variables here insteadThe default constructor is called that because, if you dont specify ANY constructors, then Java includes one by defaultDefault constructors do not take parameters

  • The specific constructorCalled the specific constructor because it is one that the user specifiesThey 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 directlyWell see why next chapter

  • Accessor methodsOur two accessor methods:

    public int getNumerator () { return numerator;}public int getDenominator () { return denominator;}

  • Mutator methodsOur two mutator methods:

    public void setNumerator (int towhat) { numerator = towhat;}public void setDenominator (int towhat) { denominator = towhat;}

  • Rational additionHow to do Rational addition:

    Our add() method:

    public Rational add (Rational other) {

    }

  • The this keywordReturns:

  • The this keywordthis is a reference to whatever object we are currently in

    Will not work in static methodsWell see why laterNote that the main() method is a static method

    While were at it, when defining a class, note that NONE of the methods were static

  • Todays demotivators

  • Rational additionHow 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);}

  • Rational subtractionHow 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);}

  • Rational multiplicationHow 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);}

  • Rational divisionHow 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);}

  • Printing it to the screenIf 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, wed like something more informative printed to the screen

    The question is: how does Java know how to print a custom class to the screen?

  • The toString() methodWhen 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 StringIf the toString() method is not found, a default one is includedHence the Rational@82ba41 from the previous slide

    So lets include our own toString() method

  • The toString() methodOur toString() method is defined as follows:

    public String toString () {return getNumerator() + "/" + getDenominator();}

    Note that the prototype must ALWAYS be defined as shownThe prototype is the public String toString()

  • Printing it to the screenNow, 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());

  • Our full Rational class

  • Our Rational class in use, part 1 of 4This code is in a main() method of a RationalDemo classFirst, we extract the values for our first Rational object:

    Scanner stdin = new Scanner(System.in);System.out.println();// extract values for rationals r and sRational 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);

  • Our Rational class in use, part 2 of 4Next, 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 didnt create another Scanner object!Doing so would be badI used the same one

  • Our Rational class in use, part 3 of 4Next, we do the arithmetic:

    // operate on r and sRational sum = r.add(s);Rational difference = r.subtract(s);Rational product = r.multiply(s);Rational quotient = r.divide(s);

  • Our Rational class in use, part 4 of 4Lastly, we print the results

    // display operation resultsSystem.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();

  • A demo of our Rational class

  • Other things we might want to add to our Rational classThe ability to reduce the fractionSo that 2/4 becomes 1/2Not as easy as it sounds!

    More complicated arithmeticSuch as exponents, etc.

    InvertSwitches the numerator and denominator

    NegateChanges the rational number into its (additive) negation

    We wont see any of that here

  • Quick surveyI felt I understood the Rational classVery wellWith some review, Ill be goodNot reallyNot at all

  • Quick surveyI feel I could define my own classVery wellWith some review, Ill be goodNot reallyNot at all

  • Quick surveyI would like to see another example of creating a class (we probably will still do it, though)Definitely!Sure, why not?Not reallyNo more! I cant take it anymore!!!!

  • Warn your grandparents!Historically, this class has been lethal to grandparents of students in the classMore often grandmothers

    This happens most around test timeAlthough occasionally around the times a big assignment is dueThe lower your course average, the more likely it is to occur

    http://biology.ecsu.ctstateu.edu/People/ConnRev.html

  • Java parameter passingThe value is copied from the actual parameter to the formal parameter

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

  • Java parameter passingConsider 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?5formal parameteractual parameter

  • Java parameter passingConsider 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.0formal parameteractual parameter

  • Java parameter passingConsider 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?5formal parameteractual parameter

  • Java parameter passingConsider 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?10formal parameteractual parameter

  • End of lecture on 16 February 2005

  • Java parameter passingConsider 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?0formal parameteractual parameter

  • Java parameter passingThe value of the actual parameter gets copied to the formal parameterThis is called pass-by-valueC/C++ is also pass-by-valueOther 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 modifiedSimilar to how the object a final reference points to can be modified

  • Quick surveyI felt I understand Java parameter passingVery wellWith some review, Ill be goodNot reallyNot at all

  • CastingWeve seen casting before:double d = (double) 3;int x = (int) d;

    Aside: duplicating an objectString 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.clone() returns an object of class Object (sic)

    More confusion: You can also have an object of class ClassThus, you can have an Object class and a Class objectGot it?

    We know its a String (as it cloned a String)Thus, we need to tell Java its 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 3That other error is because String does not have a .clone() methodNot all classes do!We just havent 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.VectorVector s = new Vector();Vector t = s.clone();Vector u = (Vector) s.clone();Causes the inconvertible types error

  • Casting, take 4What happens with the following code?Vector v = new Vector();String s = (String) v;

    Java will encounter a compile-time errorinconvertible types

    What happens with the following code?Vector v = new Vector();String s = (String) v.clone();

    Java will encounter a RUN-time errorClassCastException

  • Quick surveyI felt I understood the material in this slide setVery wellWith some review, Ill be goodNot reallyNot at all

  • Quick surveyThe pace of the lecture for this slide set wasFastAbout rightA little slowToo slow

  • Quick surveyHow interesting was the material in this slide set? Be honest!Wow! That was SOOOOOOO cool!Somewhat interestingRather boringZzzzzzzzzzz

  • Todays demotivators

    A JFrame is the principal way in Java to represent a titled, bordered graphical window. Class JFrame is part of the standard package swing. The swing package is one of several APIs (application programmer interfaces) that comprise the Java Foundations Classes (JFC). Although now part of the Java standard, the Java Foundation Classes are extensions of the original Java specification. Because it is an extension, the swing package is found at javax.swing.

    Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.private int widthRepresents width of the rectangle to be displayed

    private int heightRepresents height of the rectangle to be displayed

    private int xRepresents x-coordinate of the upper-left-hand corner of the rectangle

    private int yRepresents y-coordinate of the upper-left-hand corner of the rectangle

    private JFrame windowRepresents the window containing the rectangle drawing

    private Color color Represents the color of the rectangle to be drawn

    Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.private int widthRepresents width of the rectangle to be displayed

    private int heightRepresents height of the rectangle to be displayed

    private int xRepresents x-coordinate of the upper-left-hand corner of the rectangle

    private int yRepresents y-coordinate of the upper-left-hand corner of the rectangle

    private JFrame windowRepresents the window containing the rectangle drawing

    private Color color Represents the color of the rectangle to be drawn

    Each instance variable is defined without specifying an initial value. Therefore, whenever a new ColoredRectangle object is to be constructed, Java first initializes the new instance variables to default values. By default, numeric instance variables are initialized to 0, boolean instance variables are initialized to false, and reference-type instance variables are initialized to null. Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.The instance variable definitions specify each of the variable to be private. This modifier indicates that direct access to the instance variables is limited to the class itself. Thus, class ColoredRectangle practices information hiding by encapsulating its attributes.

    Defining instance variables to be private is a standard practice. When attributes are private, other classes are forced to use the classs interface methods to manipulate its attributes. Those interface methods normally are programmed to ensure that the requested manipulations are valid. Because the initial definition of class ColoredRectangle does not provide any methods to give access to the attributes, once a ColoredRectangle is constructed it is immutable. In Section , we introduce several ColoredRectangle methods for accessing and modifying the attributes of a ColoredRectangle object.

    Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.private int widthRepresents width of the rectangle to be displayed

    private int heightRepresents height of the rectangle to be displayed

    private int xRepresents x-coordinate of the upper-left-hand corner of the rectangle

    private int yRepresents y-coordinate of the upper-left-hand corner of the rectangle

    private JFrame windowRepresents the window containing the rectangle drawing

    private Color color Represents the color of the rectangle to be drawn

    Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.private int widthRepresents width of the rectangle to be displayed

    private int heightRepresents height of the rectangle to be displayed

    private int xRepresents x-coordinate of the upper-left-hand corner of the rectangle

    private int yRepresents y-coordinate of the upper-left-hand corner of the rectangle

    private JFrame windowRepresents the window containing the rectangle drawing

    private Color color Represents the color of the rectangle to be drawn

    Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.private int widthRepresents width of the rectangle to be displayed

    private int heightRepresents height of the rectangle to be displayed

    private int xRepresents x-coordinate of the upper-left-hand corner of the rectangle

    private int yRepresents y-coordinate of the upper-left-hand corner of the rectangle

    private JFrame windowRepresents the window containing the rectangle drawing

    private Color color Represents the color of the rectangle to be drawn

    The rendering is accomplished by first accessing the graphical context in which the drawing commands are to be issued. A graphical context is of type java.awt.Graphics.A Graphics object provides all the necessary information for carrying out a rendering request (e.g., color, component on which the rendering is to occur, font, etc.). Besides encapsulating such information, Graphics objects have a variety of methods for drawing rectangles, lines, polygons, arcs, ovals, and strings.Access to the graphical context of the window is obtained through JFrame instance method getGraphics(), Graphics g = window.getGraphics();

    Variable g is a variable whose scope of use is local to method paint(). Such a limitation is not imposed on instance variables. Their scope of use is the entire class.

    Thus, when an instance method is being executed, the attributes of the object associated with the invocation are accessed and manipulated. This property of instance methods is of paramount importance in the object-oriented programming paradigm. It is what enables objects to have behaviors. Therefore, it is crucial when examining code that you understand what object is being manipulated.

    In a transfer of control to method setWidth(), its single statement method body is executed. The statement assigns the value of formal parameter w to instance variable width. The particular instance variable that is updated, is the one belonging to the ColoredRectangle object initiating the invocation. After executing the statement body, Java transfers the flow of control back to the code segment that invoked the method. A depiction of an invocation process is given in Figure .

    Each instance variable is defined without specifying an initial value. Therefore, whenever a new ColoredRectangle object is to be constructed, Java first initializes the new instance variables to default values. By default, numeric instance variables are initialized to 0, boolean instance variables are initialized to false, and reference-type instance variables are initialized to null. Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null.The instance variable definitions specify each of the variable to be private. This modifier indicates that direct access to the instance variables is limited to the class itself. Thus, class ColoredRectangle practices information hiding by encapsulating its attributes.

    Defining instance variables to be private is a standard practice. When attributes are private, other classes are forced to use the classs interface methods to manipulate its attributes. Those interface methods normally are programmed to ensure that the requested manipulations are valid. Because the initial definition of class ColoredRectangle does not provide any methods to give access to the attributes, once a ColoredRectangle is constructed it is immutable. In Section , we introduce several ColoredRectangle methods for accessing and modifying the attributes of a ColoredRectangle object.