174
1 Classes Chapter 6 Spring 2007 CS 101 Aaron Bloomfield

Classes

Embed Size (px)

DESCRIPTION

Classes. Chapter 6 Spring 2007 CS 101 Aaron Bloomfield. The Car class. More on classes vs. objects. 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 - PowerPoint PPT Presentation

Citation preview

  • ClassesChapter 6Spring 2007CS 101Aaron Bloomfield

  • The Car class

  • 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 c = 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

  • Alien SongAlienSong.mpg

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

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

  • End of lecture on 19 March 2007

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

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

    Well see why one uses these later in this slide set

    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

  • Todays demotivators

  • 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 simplerMath.abs() returns the absolute value

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

  • Setting both positions at once

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

    Notice that to modify the instance variables, the mutator methods are used

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

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

  • 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 actionCarGUI.java

  • How well do you feel you understand the Car class?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • Cubic TragedyCubic_tragedy_m640.mov

  • Miscellaneous Stuff

  • What Im not expecting you to know yetWhat 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 later

    Why instance variables are supposed to be privateJust know that its a good programming practice, and follow itAgain, well see why soon

  • TerminologyAn attribute of a class can be called:Instance variable or class variable Well see the difference laterStatic variable (or static field)Synonymous with class variableFieldGenerally means either typeVariableAlso means either typeAttributeProperty

    Argh!I will generally use the terms variable or field when I am not differentiating between the twoAnd instance variable/field and class variable/field when I am

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

  • Running a class without a main() methodConsider the Car classIt had no main() method!The main() method was in the CarSimulation (or CarGUI) class

    So lets try running it

  • Program DemoCar.java

  • Variable initializationA local variable is NOT initialized to a default valueThis is any variable declared within a methodOr within a block within a methodThis is pretty stupid, in my opinion

    Parameters are initialized to whatever value they are passed

    Instance and class variables are initialized to default valuesNumbers to zero, booleans to false, references to nullThis means any field in a classEither class variables or instance variables

  • How well do you feel you understand creating classes so far?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • End of lecture on 21 March 2007

  • The Circle classIntroducing static-ness, visibilities, etc.

  • A Circle classWe are going to develop a Circle classPerhaps for use in a graphics program

    Why?Partly to review creating classesGo over some topics that were a bit fuzzyConstructors and creating objectsShow why one uses the get/set methods instead of directly modifying the instance variablesDiscuss visibilities (public, private, etc.)Discuss the static keyword

  • Circle class propertiesWhat properties does a circle have?RadiusPI = 3.141592653589793234Color (if plotting in a graphics program)(x,y) location

    These properties will become instance variablesWe are only going to play with the first two (radius and PI) in this exampleThus, we are ignoring the color and location

  • Our Circle classCircle c = new Circle();

    public class Circle {double radius;double PI = 3.1415926536;}Note the fieldsare not staticNote the radius field is not initialized by usWere ignoring the public for now

  • Accessing our Circle objectAny variable or method in an object can be accessed by using a periodThe period means follow the reference

    Example: System.in

    Example: System.out.println (c.radius);

    Example: c.PI = 4;

    This is bad PI should have been declared final(this will be done later)

  • Whats the output?public class Circle {double radius;double PI = 3.1415926536;}

    public class CircleTest {public static void main (String[] args) { int x;Circle c = new Circle();System.out.println (x);}}

    When a variable is declared as part of a method, Java does not initialize it to a default valueJava will give a variable not initialized error

  • Whats the output now?public class Circle {double radius;double PI = 3.1415926536;}

    public class CircleTest {public static void main (String[] args) { int x;Circle c = new Circle();System.out.println (c.radius);}}

    When a variable is declared as part of a class, Java does initialize it to a default valueJava outputs 0.0!

  • Whats going on?A (method) variable needs to be initialized before it is usedUsually called a local variableA instance variable is automatically initialized by JavaAll numbers are initialized to 0, booleans to false, etc.This is a bit counter-intuitive

  • Circle class behaviorsWhat do we want to do with (and to) our Circle class?Create circlesModify circles (mutators)Find out about our circles properties (accessors)Find the area of the circlePlot it on the screen (or printer)A few others

    These will be implemented as methods

  • Calling the Circle constructorTo create a Circle object:

    Circle c1 = new Circle();

    This does four things:Creates the c1 referenceCreates the Circle objectMakes the c1 reference point to the Circle objectCalls the constructor with no parameters (the default constructor)

    The constructor is always the first method called when creating (or constructing) an object

  • Calling the Circle constructorTo create a Circle object:

    Circle c1 = new Circle(2.0);

    This does four things:Creates the c1 referenceCreates the Circle objectMakes the c1 reference point to the Circle objectCalls the constructor with 1 double parameters (the specific constructor)

    The constructor is always the first method called when creating (or constructing) an object

  • ConstructorsRemember, the purpose of the constructor is to initialize the instance variablesPI is already set, so only radius needs setting

    public Circle() {radius = 1.0;}

    public Circle (double r) {radius = r;}

    Note there is no return type for constructorsNote that the constructorname is the EXACT sameas the class nameNote that there are two methods with the same name!

  • What happens in memoryConsider: Circle c = new Circle();A double takes up 8 bytes in memoryThus, a Circle object takes up 16 bytes of memoryAs it contains two doublesShorthand representation

  • Circle class: our class so farpublic class Circle {

    double radius;double PI = 3.1415926536;

    public Circle() {radius = 1.0;}

    public Circle (double r) {radius = r;}

    }

  • How well do you feel you understand the constructors?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • New 2005 demotivatiors!

  • Circle class: our class so farpublic class Circle {

    double radius;double PI = 3.1415926536;

    public Circle() {radius = 1.0;}

    public Circle (double r) {radius = r;}

    }

  • Consider the following codepublic class CircleTest {public static void main (String[] args) { Circle c1 = new Circle();Circle c2 = new Circle();Circle c3 = new Circle();Circle c4 = new Circle();}}

  • What happens in memoryThere are 4 Circle objects in memoryTaking up a total of 4*16 = 64 bytes of memory

  • Consider the following codepublic class CircleTest {public static void main (String[] args) { Circle c1 = new Circle();//...Circle c1000000 = new Circle();}}

    public class CircleTest {public static void main (String[] args) { Vector v = new Vector();for ( int i = 0; i < 1000000; i++ )v.add (new Circle());}}

    These programs create 1 million Circle objects!

  • What happens in memoryThere are 1 million Circle objects in memoryTaking up a total of 1,000,000*16 16 Mb of memoryNote that the final PI field is repeated 1 million times

  • The use of static for fieldsIf a variable is static, then there is only ONE of that variable for ALL the objectsThat variable is shared by all the objectsTotal memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles)Total memory usage: 16 bytes (1+1=2 doubles)Total memory usage: 40 bytes (4+1=5 doubles)c1000000c4PI3.1415926536

  • More on static fieldsWhat does the following printNote that PI is not final

    Circle c1 = new Circle();Circle c2 = new Circle();Circle c3 = new Circle();Circle c4 = new Circle();c1.PI = 4.3;System.out.println (c2.PI);

    It prints 4.3Note you can refer to static fields byobject.variable

  • Even more on static fieldsThere is only one copy of a static field no matter how many objects are declared in memoryEven if there are zero objects declared!The one field is common to all the objects

    Static variables are called class variablesAs there is one such variable for all the objects of the classWhereas non-static variables are called instance variables

    Thus, you can refer to a static field by using the class name:Circle.PI

  • Even even more on static fieldsThis program also prints 4.3:

    Circle c1 = new Circle();Circle c2 = new Circle();Circle c3 = new Circle();Circle c4 = new Circle();Circle.PI = 4.3;System.out.println (c2.PI);

  • Even even even more on static fieldsWeve seen static fields used with their class names:System.in(type: InputStream)System.out(type: OutputStream)Math.PI(type: double)Integer.MAX_VALUE(type: int)Game.BOARD_X_COORD(in HW J6)

  • How well do you feel you understand static-ness?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • Hand Paintings

  • Back to our Circle classpublic class Circle {double radius;final static double PI = 3.1415926536;

    public Circle() {radius = 1.0;}

    public Circle (double r) {radius = r;}

    }

    But it doesnt do much!Note that PI is now final and static

  • Adding a methodpublic class Circle {double radius;final static double PI = 3.1415926536;

    // Constructors...

    double computeArea () { return PI*radius*radius; }

    }Note that a (non-static) method can use both instance and class variables

  • Using that methodpublic class CircleTest {public static void main (String[] args) {Circle c = new Circle();c.radius = 2.0;double area = c.computeArea();System.out.println (area); }}Prints 12.566370614356

  • What happens when that method is calledpublic class Circle {double radius;final static double PI = 3.1415926536;

    public Circle() {radius = 1.0;}

    // other constructor

    double computeArea () { return PI*radius*radius; }

    }

    public class CircleTest {public static void main (String[] args) {Circle c = new Circle();c.radius = 2.0;double area = c.computeArea();System.out.println (area); }}

  • Review of our Circle classpublic class Circle {

    double radius;final static double PI = 3.1415926536;

    public Circle() {}

    public Circle (double r) {radius = r;}

    double computeArea () { return PI*radius*radius; }

    }Slight change from before

  • A note about methods/variable orderWithin a method, a variable must be declared before it is used

    In a class, methods and variables can be declared in any orderThis is different than C++

  • End of lecture on 23 March 2007

  • Review of static for fieldsIf a variable is static, then there is only ONE of that variable for ALL the objectsThat variable is shared by all the objectsTotal memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles)Total memory usage: 16 bytes (1+1=2 doubles)Total memory usage: 40 bytes (4+1=5 doubles)c1000000c4PI3.1415926536

  • Adding another methoddouble oneOverRadius() { return 1.0/radius;}

    I couldnt think of a good reason to divide something by the radius

  • What happens now?Code in class CircleTests main() method

    Circle c = new Circle(); // c.radius is now 0.0System.out.println (c.oneOverRadius());

    Java wont crash, but many other programming languages (C and C++, in particular) willSo well call this a crash for the sake of this lecture

    Java prints InfinityNot what we wanted, though!

  • One way to fix thispublic class Circle {double radius = 1.0;final static double PI = 3.1415926536;

    // Constructors...

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius;}

    }Note that the radius variable is now initialized to 1.0

  • Back to our programThis code will now run properly:

    Circle c = new Circle(); // c.radius = 1.0System.out.println (c.oneOverRadius());

    But this code will crash:

    Circle c = new Circle(); // c.radius = 1.0c.radius = 0.0;System.out.println (c.oneOverRadius());

  • Where the crash occurspublic class CircleTest {

    public static void main (String[] args) {

    Circle c = new Circle(); // c.radius = 1.0

    c.radius = 0.0;

    System.out.println (c.oneOverRadius());}}public class Circle {double radius = 1.0;final static double PI = 3.1415926536;

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius;}

    Here is the badly written codeHere is where the crash occurs

  • Motivation for private fieldsProblem: We do not want people using our Circle class to be able to modify the fields on their own

    Solution: Dont allow other code to modify the radius fieldGive it private visibility

    private means that only code within the class can modify the field

  • One way to fix thispublic class Circle {private double radius = 1.0;final static double PI = 3.1415926536;

    // Constructors...

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius;}

    }Note that the radius variable is now private

  • Todays demotivators

  • Back to our programThis code will now not compile:

    Circle c = new Circle(); // c.radius = 1.0c.radius = 0.0;System.out.println (c.oneOverRadius());

    Java will give a compile-time error:radius has private access in Circle

  • Back to our programThis code will also not compile:

    Circle c = new Circle(); // c.radius = 1.0System.out.println (c.radius);

    Java will give the same compile-time error:radius has private access in Circle

  • The problem nowBut now you cant modify a Circles radius!Or find out what it is

    Solution: Use a get/set methods in Circle:

    A mutator method:

    void setRadius (double r) { radius = r;}

    An accessor method:

    double getRadius () { return radius;}

  • Our Circle class so farpublic class Circle { private double radius = 1.0; final static double PI = 3.1415926536;

    // Constructors...

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius; }

    void setRadius (double r) { radius = r; } double getRadius () { return radius; }}

  • Using the get/set methodspublic class CircleTest {

    public static void main (String[] args) {

    Circle c = new Circle();

    c.setRadius (1.0);

    System.out.println (c.computeArea());

    System.out.println (c.getRadius());

    }}public class Circle { private double radius = 1.0; final static double PI = 3.1415926536;

    double computeArea () { return PI*radius*radius; }

    double oneOverRadius() { return 1.0/radius; }

    void setRadius (double r) { radius = r; } double getRadius () { return radius; }}Here a method is invokedHere the change to radius occurs

  • Wait! Another problem!public class CircleTest {

    public static void main (String[] args) {

    Circle c = new Circle();

    c.setRadius (0.0);

    System.out.println (c.oneOverRadius());

    }}Here is the problem now

  • This problem is easily fixedChange the setRadius() method to the following

    void setRadius (double r) {if ( r > 0.0 ) radius = r;else radius = 1.0;}

    Now there is (almost) no way for code outside the Circle class to change the radius to zero

    This is the purpose of mutatorsTo prevent changing the fields to a bad valueWell see another motivation in a bit

  • Visibilities in JavaThere are four visibilities:private: Only code within the same class can access the field or methodNote: access means reading or writing the field, or invoking the method

    public: Any code, anywhere, can access the field or method

    protected: Used with inheritanceWe wont get to that this semester

    default: Almost the same as publicThis is the default (duh!)Note that it cant be specified like the othersAlso called package

  • A few notes on visibilitiesYou can NOT specify visibilities for method variablesAny method variable can only be accessed within that methodThink of it as public within the method (after its defined) and private outside the method

    You can also specify visibilities for methods and classesWe will see this a bit in this course

  • How well do you feel you understand visibilities?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • DeCSS: The program#include typedef unsigned int uint; char ctb[512]="33733b2663236b763e7e362b6e2e667bd393db0643034b96de9ed60b4e0e4\ 69b57175f82c787cf125a1a528fca8ac21fd999d10049094190d898d001480840913d7d35246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd4054c0c449559195180c989c11058185\ 081c888c011d797df0247074f92da9ad20f4a0a429f53135b86c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6abeeaee6fb37773f2267276f723a7a322f6a2a627fb9f9b1a0e9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485cc8cc415bdfdb5a4edade5f4bcfcb4a5e\ cace4f539793120692961703878302168286071b7f7bfa2e7a7eff2bafab2afeaaae2ff"; typedef unsigned char uchar;uint tb0[11]={5,0,1,2,3,4,0,1,2,3,4};uchar* F=NULL; uint lf0,lf1,out;void ReadKey(uchar* key){int i;char hst[3]; hst[2]=0;if(F==\ NULL){F=malloc(256);for(i=0;i21)^(lf1>>24))&1;lf0=(lf0
  • DeCSS: The shirt (and tie!)

  • DeCSS: The poemHow to decrypt aDVD: in haiku form.(Thanks, Prof. D. S. T.)------------------------

    (I abandon myexclusive rights to make orperform copies of

    this work, U. S. CodeTitle Seventeen, sectionOne Hundred and Six.)

    Muse! When we learned tocount, little did we know allthe things we could do

    some day by shufflingthose numbers: Pythagorassaid "All is number"

    long before he sawcomputers and their effects,or what they could doTable Zero is:Five, zero, one, two, three, four,oh, one, two, three, four.

    Table One is long:two to the eighth power bytes.Ready? Here they are:

    Fifty one; then onehundred fifteen; fifty nine;thirty eight; ninety

    nine; thirty five; onehundred seven; one hundredeighteen; sixty two;

    one hundred twentysix; fifty four; forty three;one hundred ten; then

  • DeCSS: The numberThe worlds first illegal prime number:

    485650789657397829309841894694286137707442087351357924019652073668698513401047237446968797439926117510973777701027447528049058831384037549709987909653955227011712157025974666993240226834596619606034851742497735846851885567457025712547499964821941846557100841190862597169479707991520048667099759235960613207259737979936188606316914473588300245336972781813914797955513399949394882899846917836100182597890103160196183503434489568705384520853804584241565482488933380474758711283395989685223254460840897111977127694120795862440547161321005006459820176961771809478113622002723448272249323259547234688002927776497906148129840428345720146348968547169082354737835661972186224969431622716663939055430241564732924855248991225739466548627140482117138124388217717602984125524464744505583462814488335631902725319590439283873764073916891257924055015620889787163375999107887084908159097548019285768451988596305323823490558092032999603234471140776019847163531161713078576084862236370283570104961259568184678596533310077017991614674472549272833486916000647585917462781212690073518309241530106302893295665843662000800476778967984382090797619859493646309380586336721469695975027968771205724996666980561453382074120315933770309949152746918356593762102220068126798273445760938020304479122774980917955938387121000588766689258448700470772552497060444652127130404321182610103591186476662963858495087448497373476861420880529443

  • DeCSS: The images

  • DeCSS: The recordingsAll this info from http://www-2.cs.cmu.edu/~dst/DeCSS/Gallery/

    Or do a Google search for decss gallery

  • DeCSS: The movie

  • Overriding methods (and constructors)Consider the following code:

    Circle c1 = new Circle (); Circle c2 = new Circle (2.0);

    Java knows which constructor to call by the list of parametersThis is called overloadingMeaning it means multiple things, depending on the context

    Weve seen overloading before:3+4Performs integer addition3.0+4.0Performs floating-point addition3+4Performs string concatenation

    The + operator is overloadedCreates a Circleof radius 1.0Creates a Circleof radius 2.0

  • Overriding methods (and constructors), take 2The following Circle constructors would not be allowed:We are assuming PI is not final for this example

    public Circle() { radius = 1.0; }

    public Circle (double r) { radius = r; }

    public Circle (double p) { PI = p; }When Circle(1.0) is called, which one is meant?

  • Using mutators in the constructorOur second constructor has a problem:

    public Circle (double r) { radius = r; }

    Consider the following code:

    Circle c = new Circle (0.0); System.out.println (c.oneOverRadius());The method is dividing by zero (again)

  • Using mutators in the constructorThis is easily fixed!

    Our revised constructors:

    public Circle() { setRadius (1.0); }

    public Circle (double r) { setRadius (r);}

    The mutator will properly set the radius (and wont set it to zero)

  • Why we always use the mutatorsConsider a modified version of our circle class:

    class Circle {double radius;double diameter;String size;

    // ...

    Our mutator now looks like this:

    Thats a lot of code to copy if you decide not to call the mutator!void setRadius (double r) { if ( radius

  • End of lecture on 30 March 2007

  • Google April Fools Day Jokes (2007)http://www.google.com/tisp/http://mail.google.com/mail/help/paper/

  • End of lecture on 2 April 2007We didnt cover any slides today. Instead, we covered:HW 7Review of exam 2The course project

  • An aside: scoping issuesConsider this class:

    class Foo {int x = 0;public Foo (int x) { x = x;}}

    Which x is being referred to in the constructor?Remember that Java will use the most recent xSo this doesnt set the instance variable!Instead, it sets the parameter equal to itself

  • An aside: scoping issuesLets modify that class:

    class Foo {int x = 0;public Foo (int x) { this.x = x;}}

    The this.x means the instance variable xAnd the x means the parameterNow this does the right thingAnother solution:

    class Foo {int x = 0;public Foo (int y) { x = y;}}

    By renaming the parameter, we achieve the same effectThis very relevant to HW 7!

  • Back to the static discussionRemember that there is one (and only one) static PI field, regardless of how many objects are declared

    Consider the following method:

    double getPI() { return PI;}

    It doesnt read or modify the state of any objectIn this example, it doesnt read/write the radius

    In fact, that particular method doesnt care anything about the objects declaredIts only accessing a static field

  • Make getPI() staticConsider the following:

    static double getPI() { return PI; }

    As the method is static, it can ONLY access static fields

    A static method does not care about the state of an objectExamples: Math.sin(), Math.tan(), Math.cos()They dont care about the state of any Math objectThey only perform the computation

  • Invoking static methodsAs with static fields, they can be called using either an object or the class name:

    Circle c = new Circle(); System.out.println (c.getPI()); System.out.println (Circle.getPI());

    Static methods are also called class methods

  • static methods and non-static fieldsConsider the following (illegal) Circle method:

    static double getRadius() { return radius; }

    And the code to invoke it:

    public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); System.out.println (Circle.getRadius()); }

  • What happening in memoryThere are 4 Circle objects in memory

    Which radius field does Circle.getRadius() want?There are 1 million Circle objects in memoryThere are no Circle objects in memoryc1000000c4PI3.1415926536

  • The main static lessonA static method cannot access or modify the state of the object it is a part of

    If you remember nothing else about static methods, remember this!

  • static and non-static rulesNon-static fields and methods can ONLY be accessed by the object nameStatic fields and methods can be accessed by EITHER the class name or the object nameNon-static methods can refer to BOTH static and non-static fieldsStatic methods can ONLY access static fields of the class they are part of

  • How well do you feel you understand static-ness?Very well! This stuff is easy!Fairly well with a little review, Ill be goodOkay. Its not great, but its not horrible, eitherNot well. Im kinda confusedNot at all. Im soooooo lost.

  • Very unofficial demotivators

  • Back to our main() method public static void main (String[] args)

    Any code anywherecan call this methodIts a static method:Cant access non-static fields or methods directlyCan be called only by the class nameThe method does not return a valueWell learn about arrays in chapter 8

  • Implications of main() being staticIt can call other static methods within the same class

    class StaticMethods { static void method1() { System.out.println (hi!); }

    public static void main (String args[]) { method1(); }}

    Note that we didnt have to prefix method1() with a objectJava assumes that it is in the same class

  • Another use of static methodsLets say we want each Circle object to have a unique identifierThe identifier will be a positive integer

    So in the Circle class, we add a instance variable:int id = 0;Thus, each Circle object will have its own id number

    To keep track of the last assigned id number, we will use a class variablestatic int lastAssignedID = 0;

    Thus, for all Circle objects created, we will have a single lastAssignedID field

  • Circle ID numbersWe can then create a method to obtain a unique ID number:

    public static int getID() { return ++lastAssignedID;}

    This method is static, and only can access static fields

    In our Circle constructors, we put the following line:

    id = getID();

  • Todays demotivators

  • Debugging Java Code

  • Debugging Java codeIn Main.java:

    public class Main { public static void main (String args[]) {Error1 e1 = new Error1();e1.foo();e1.bar(); }}

    In Error1.java:

    public class Error1 { public Error1() { }

    public void foo() {String s = null;System.out.println (s.substring(5)); } public void bar() {foo(); }}

    This will cause a null pointer exception!

  • Program DemoErrors/Main.java

  • What the error output meansThe error output:

    Exception in thread "main" java.lang.NullPointerException at Error1.foo(Error1.java:6) at Main.main(Main.java:4)

    This means that:A null point exception happenedIn the Error1.foo() method on line 6 of Error1.javaAnd that was called from Main.main() on line 4 of Main.java

    Note that the top two lines tell the most useful information

    So we comment out the e1.foo() call in main()

  • Debugging Java codeIn Main.java:

    public class Main { public static void main (String args[]) {Error1 e1 = new Error1();//e1.foo();e1.bar(); }}

    In Error1.java:

    public class Error1 { public Error1() { }

    public void foo() {String s = null;System.out.println (s.substring(5)); } public void bar() {foo(); }}

  • Program DemoErrors/Main.java

  • What the error output meansThe error output:

    Exception in thread "main" java.lang.NullPointerException at Error1.foo(Error1.java:6) at Error1.bar(Error1.java:10) at Main.main(Main.java:5)

    This means that:A null point exception happenedIn the Error1.foo() method on line 6 of Error1.javaAnd that was called from Error1.bar() on line 10 of Error.javaAnd that was called from Main.main() on line 5 of Main.java

    Again, note that the top two lines tell the most useful information

  • Hondas best commercialcog.mov

  • More on methods

  • Calling a methodConsider two Strings:

    String s = foo;String t = bar;

    Calling s.substring(2) is different than calling t.substring(2)

    Why?

    Because of the object it is being called out ofThe method works the same in both cases (returns the substring)But it returns different resultsWhenever we are calling a method, we also need to know which object we are calling it out of

  • Return valuesMany methods return a valueMath.cos()String.valueOf()

    Consider: double d = Math.cos (90 * Math.PI/180.0);

    Lets consider the Math.cos() method

    public double cos (double a) { double c = 0.0; // compute cos somehow into a variable c return c;}

    The value c in the cos() method is copied into d

  • The return keywordThe return keyword does a few things:Immediately terminate the current methodPass the value back to whoever called the method

    You can have a return anywhere you wantInside loops, ifs, etc.

    You can have as may returns as you want as well:

    public String foo (int x) { if ( x == 1 ) return one; else if ( x == 2 ) return two; else return other;}

  • More on returnsConsider this class:

    public class Foo { // Default constructor omitted on this slide public String bar (String s) { String t = CS 101 + + s; return t; }}

    And the code to invoke it:

    Foo w = new Foo();String x = rules;String y = foo.bar (x);System.out.println (y);

    What happens in memory?

  • Foo w = new Foo();String x = rules;String y = w.bar (x);System.out.println (y);Foo w = new Foo();String x = rules;String y = w.bar (x);System.out.println (y); public String bar (String s) { String t = CS 101 + + s; return t; } public String bar (String s) { String t = CS 101 + + s; return t; tthis+ Foo()+ bar (String s): String+ s

  • Returning an object from a methodWe could rewrite our bar() method a number of ways:

    public String bar (String s) { String t = CS 101 + + s; return t; }

    public String bar (String s) { return new String (CS 101 + + s); }

    public String bar (String s) { return CS 101 + + s; }

  • Returning a non-object from a methodIn other words, returning a primitive type from a method

    public foo () { // ... return x + y;}

    This method evaluates x+y, then returns that value to the caller

  • Chapter 2: Computer bugs

  • Off to arrays.

  • Yale vs. Harvard

  • Rational class

  • What weve seen so farAn example of creating a classCar

    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 later

  • 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 so far were static

  • 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 additionThe following method is equivalent:

    Our add() method:

    public Rational add (Rational other) { int a = getNumerator(); int b = getDenominator(); int c = other.getNumerator(); int d = other.getDenominator(); return new Rational (a*d+b*c, b*d);}

  • Rational additionThe following method is equivalent, but not preferred:

    Our add() method:

    public Rational add (Rational other) { int a = numerator; int b = denominator; int c = other.numerator; int d = other.nenominator; return new Rational (a*d+b*c, b*d);}

  • Rational additionThe following method is equivalent, but not preferred:

    Our add() method:

    public Rational add (Rational other) { int a = this.numerator; int b = this.denominator; int c = other.numerator; int d = other.nenominator; 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 (mostly) 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 classRationalDemo.java

  • 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

  • How well do you feel you understand the Rational class?Very well! This stuff is so easy.With a little review, Ill be good.Not very well at all.Im so lost. Whats a class again?Id rather not answer this question, thanks.

    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.