Classes - PowerPoint PPT Presentation

About This Presentation
Title:

Classes

Description:

Position (x,y) Fuel in tank. We will implement these ... A mutator that sets both the x and y positions at the same time. A means to 'use' the Car's fuel ... – PowerPoint PPT presentation

Number of Views:87
Avg rating:3.0/5.0
Slides: 175
Provided by: jimco60
Category:
Tags: classes

less

Transcript and Presenter's Notes

Title: Classes


1
Classes
  • Chapter 6
  • Spring 2007
  • CS 101
  • Aaron Bloomfield

2
The Car class
3
More on classes vs. objects
4
A new example creating a Car class
  • What properties does a car have in the real
    world?
  • Color
  • Position (x,y)
  • Fuel in tank
  • We will implement these properties in our Car
    class
  • public class Car
  • private Color color
  • private int xpos
  • private int ypos
  • private int fuel
  • //...

5
Cars instance variables
  • public class Car
  • private Color color
  • private int xpos
  • private int ypos
  • private int fuel
  • //...

6
Instance variables and attributes
  • Default initialization
  • If the variable is within a method, Java does NOT
    initialize it
  • If the variable is within a class, Java
    initializes it as follows
  • Numeric instance variables initialized to 0
  • Logical instance variables initialized to false
  • Object instance variables initialized to null

7
Car behaviors or methods
  • What can a car do? And what can you do to a car?
  • Move it
  • Change its x and y positions
  • Change its color
  • Fill it up with fuel
  • For our computer simulation, what else do we want
    the Car class to do?
  • Create a new Car
  • Plot itself on the screen
  • Each of these behaviors will be written as a
    method

8
Creating a new car
  • To create a new Car, we call
  • Car c new Car()
  • Notice this looks like a method
  • You are calling a special method called a
    constructor
  • A constructor is used to create (or construct) an
    object
  • It sets the instance variables to initial values
  • The constructor
  • public Car()
  • fuel 1000
  • color Color.BLUE

9
Constructors
  • public Car()
  • fuel 1000
  • color Color.BLUE

No return type!
EXACT same name as class
For now, all constructors are public
10
Our Car class so far
  • public class Car
  • private Color color
  • private int xpos
  • private int ypos
  • private int fuel
  • public Car()
  • fuel 1000
  • color Color.BLUE
  • public class Car
  • private Color color
  • Color.BLUE
  • private int xpos
  • private int ypos
  • private int fuel 1000
  • public Car()

11
Our Car class so far
  • public class Car
  • private Color color
  • Color.BLUE
  • private int xpos 0
  • private int ypos 0
  • private int fuel 1000
  • public Car()
  • Called the default constructor
  • The default constructor has no parameters
  • If you dont include one, Java will SOMETIMES put
    one there automatically

12
Alien Song
  • AlienSong.mpg

13
Another constructor
  • Another constructor
  • public Car (Color c, int x, int y, int f)
  • color c
  • xpos x
  • ypos y
  • fuel f
  • This constructor takes in four parameters
  • The instance variables in the object are set to
    those parameters
  • This is called a specific constructor
  • An constructor you provide that takes in
    parameters is called a specific constructor

14
Our Car class so far
  • public class Car
  • private Color color
  • Color.BLUE
  • private int xpos 0
  • private int ypos 0
  • private int fuel 1000
  • public Car()
  • public Car (Color c, int x, int y, int f)
  • color c
  • xpos x
  • ypos y
  • fuel f

15
Using our Car class
  • Now we can use both our constructors
  • Car c1 new Car()
  • Car c2 new Car (Color.BLACK, 1, 2, 500)

16
So what does private mean?
Note that its a different class!
  • Consider the following code
  • public class CarSimulation
  • public static void main (String args)
  • Car c new Car()
  • System.out.println (c.fuel)
  • Recall that fuel is a private instance variable
    in the Car class
  • Private means that code outside the class CANNOT
    access the variable
  • For either reading or writing
  • Java will not compile the above code
  • If fuel were public, the above code would work

17
End of lecture on 19 March 2007
18
So how do we get the fuel of a Car?
  • Via accessor methods in the Car class
  • public int getFuel()
  • return fuel
  • public Color getColor()
  • return color
  • As these methods are within the Car class, they
    can read the private instance variables
  • As the methods are public, anybody can call them

public int getYPos() return ypos public
int getXPos() return xpos
19
So how do we set the fuel of a Car?
  • Via mutator methods in the Car class
  • public void setFuel (int f)
  • fuel f
  • public void setColor (Color c)
  • color c
  • As these methods are within the Car class, they
    can read the private instance variables
  • As the methods are public, anybody can call them

public void setXPos (int x) xpos
x public void setYPos (int y) ypos y
20
Why use all this?
  • These methods are called a get/set pair
  • Used with private variables
  • Well see why one uses these later in this slide
    set
  • Our Car so far

21
Back to our specific constructor
  • public class Car
  • private Color color
  • Color.BLUE
  • private int xpos 0
  • private int ypos 0
  • private int fuel 1000
  • public Car (Color c,
  • int x, int y, int f)
  • color c
  • xpos x
  • ypos y
  • fuel f

public class Car private Color color
Color.BLUE private int xpos 0 private
int ypos 0 private int fuel 1000 public
Car (Color c, int x, int y, int f)
setColor (c) setXPos (x) setYPos
(y) setFuel (f)
22
Back to our specific constructor
  • Using the mutator methods (i.e. the set
    methods) is the preferred way to modify instance
    variables in a constructor
  • Well see why later

23
Todays demotivators
24
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 time
  • A means to use the Cars fuel
  • A 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

25
Using the Cars fuel
  • Whenever the Car moves, it should burn some of
    the fuel
  • For each pixel it moves, it uses one unit of fuel
  • We could make this more realistic, but this is
    simpler
  • Math.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
26
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

27
Drawing the Car
  • The simple way to have the Car draw itself
  • public void paint (Graphics g)
  • g.setColor (color)
  • g.fillRect (xpos-50, ypos-100,
  • 100, 200)
  • This draws a single rectangle that is 100 by 200
    pixels in size
  • Lets use constants for the cars height and
    width...

28
Drawing the Car
  • A better version
  • private final int CAR_WIDTH 100
  • private final int CAR_HEIGHT 200
  • public void paint (Graphics g)
  • g.setColor (color)
  • g.fillRect (getXPos()-CAR_WIDTH/2,
  • getYPos()-CAR_HEIGHT/2,
  • CAR_WIDTH, CAR_HEIGHT)
  • This makes it easier to change the car size
  • We could have made the car size instance
    variables and set them via mutators
  • Lets add tires!

29
Drawing the Car
  • private final int CAR_WIDTH 100
  • private final int CAR_HEIGHT 200
  • private final int TIRE_WIDTH 20
  • private final int TIRE_HEIGHT 40
  • private final int TIRE_OFFSET 20
  • public void paint (Graphics g)
  • g.setColor (color)
  • g.fillRect (getXPos()-CAR_WIDTH/2,
  • getYPos()-CAR_HEIGHT/2,
  • CAR_WIDTH, CAR_HEIGHT)
  • // Draw the tires
  • g.setColor (Color.BLACK)
  • g.fillRect (getXPos()-(CAR_WIDTH/2TIRE_WIDTH
    ),
  • getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET),
    TIRE_WIDTH, TIRE_HEIGHT)
  • g.fillRect (getXPos()-(CAR_WIDTH/2TIRE_WIDTH
    ),
  • getYPos()(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEI
    GHT),
  • TIRE_WIDTH, TIRE_HEIGHT)

Dont worry about this just know that it draws
four tires
30
What happens when the car runs out of fuel?
  • We could do a number of things
  • Not allow the car to move anymore
  • Print out a message saying, fill me up!
  • Well color the car red
  • Well insert the following code at the beginning
    of the paint() method
  • if ( fuel
  • color Color.RED

31
Drawing the Car
  • private final int CAR_WIDTH 100
  • private final int CAR_HEIGHT 200
  • private final int TIRE_WIDTH 20
  • private final int TIRE_HEIGHT 40
  • private final int TIRE_OFFSET 20
  • public void paint (Graphics g)
  • if ( fuel
  • 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/2TIRE_WIDTH
    ),
  • getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET),
    TIRE_WIDTH, TIRE_HEIGHT)

32
Our car in action
  • CarGUI.java

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

34
Cubic Tragedy
  • Cubic_tragedy_m640.mov

35
Miscellaneous Stuff
36
What Im not expecting you to know yet
  • What the static keyword means
  • And why the main() method is
  • And why other methods are not
  • Why you should always call the mutator methods,
    instead of setting the field directly
  • Just know that its a good programming practice,
    and follow it
  • Well see why later
  • Why instance variables are supposed to be private
  • Just know that its a good programming practice,
    and follow it
  • Again, well see why soon

37
Terminology
  • An attribute of a class can be called
  • Instance variable or class variable
  • Well see the difference later
  • Static variable (or static field)
  • Synonymous with class variable
  • Field
  • Generally means either type
  • Variable
  • Also means either type
  • Attribute
  • Property
  • Argh!
  • I will generally use the terms variable or field
    when I am not differentiating between the two
  • And instance variable/field and class
    variable/field when I am

38
The main() method
  • Consider a class with many methods
  • public class WhereToStart
  • public static void foo (int x)
  • // ...
  • public static void bar ()
  • // ...
  • public static void main (String args)
  • // ...
  • Where does Java start executing the program?
  • Always at the beginning of the main() method!

39
Running a class without a main() method
  • Consider the Car class
  • It had no main() method!
  • The main() method was in the CarSimulation (or
    CarGUI) class
  • So lets try running it

40
Program Demo
  • Car.java

41
Variable initialization
  • A local variable is NOT initialized to a default
    value
  • This is any variable declared within a method
  • Or within a block within a method
  • This is pretty stupid, in my opinion
  • Parameters are initialized to whatever value they
    are passed
  • Instance and class variables are initialized to
    default values
  • Numbers to zero, booleans to false, references to
    null
  • This means any field in a class
  • Either class variables or instance variables

42
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 good
  • Okay. Its not great, but its not horrible,
    either
  • Not well. Im kinda confused
  • Not at all. Im soooooo lost.

43
End of lecture on 21 March 2007
44
The Circle class
  • Introducing static-ness, visibilities, etc.

45
A Circle class
  • We are going to develop a Circle class
  • Perhaps for use in a graphics program
  • Why?
  • Partly to review creating classes
  • Go over some topics that were a bit fuzzy
  • Constructors and creating objects
  • Show why one uses the get/set methods instead of
    directly modifying the instance variables
  • Discuss visibilities (public, private, etc.)
  • Discuss the static keyword

46
Circle class properties
  • What properties does a circle have?
  • Radius
  • PI 3.141592653589793234
  • Color (if plotting in a graphics program)
  • (x,y) location
  • These properties will become instance variables
  • We are only going to play with the first two
    (radius and PI) in this example
  • Thus, we are ignoring the color and location

47
Our Circle class
Circle c new Circle() public class Circle
double radius double PI 3.1415926536
Note the radius field is not initialized by us
Note the fields are not static
Were ignoring the public for now
48
Accessing our Circle object
  • Any variable or method in an object can be
    accessed by using a period
  • The 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)
49
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 value

Java will give a variable not initialized
error
50
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 value

Java outputs 0.0!
51
Whats going on?
  • A (method) variable needs to be initialized
    before it is used
  • Usually called a local variable
  • A instance variable is automatically initialized
    by Java
  • All numbers are initialized to 0, booleans to
    false, etc.
  • This is a bit counter-intuitive

52
Circle class behaviors
  • What do we want to do with (and to) our Circle
    class?
  • Create circles
  • Modify circles (mutators)
  • Find out about our circles properties
    (accessors)
  • Find the area of the circle
  • Plot it on the screen (or printer)
  • A few others
  • These will be implemented as methods

53
Calling the Circle constructor
  • To create a Circle object
  • Circle c1 new Circle()
  • This does four things
  • Creates the c1 reference
  • Creates the Circle object
  • Makes the c1 reference point to the Circle
    object
  • Calls the constructor with noparameters (the
    defaultconstructor)
  • The constructor is always the first method called
    when creating (or constructing) an object

54
Calling the Circle constructor
  • To create a Circle object
  • Circle c1 new Circle(2.0)
  • This does four things
  • Creates the c1 reference
  • Creates the Circle object
  • Makes the c1 reference point to the Circle
    object
  • Calls the constructor with 1double parameters
    (the specificconstructor)
  • The constructor is always the first method called
    when creating (or constructing) an object

55
Constructors
  • Remember, the purpose of the constructor is to
    initialize the instance variables
  • PI 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 constructors
Note that the constructor name is the EXACT
same as the class name
Note that there are two methods with the same
name!
56
What happens in memory
  • Consider Circle c new Circle()
  • A double takes up 8 bytes in memory
  • Thus, a Circle object takes up 16 bytes of memory
  • As it contains two doubles

Shorthand representation
57
Circle class our class so far
  • public class Circle
  • double radius
  • double PI 3.1415926536
  • public Circle()
  • radius 1.0
  • public Circle (double r)
  • radius r

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

59
New 2005 demotivatiors!
60
Circle class our class so far
  • public class Circle
  • double radius
  • double PI 3.1415926536
  • public Circle()
  • radius 1.0
  • public Circle (double r)
  • radius r

61
Consider the following code
  • public class CircleTest
  • public static void main (String args)
    Circle c1 new Circle()
  • Circle c2 new Circle()
  • Circle c3 new Circle()
  • Circle c4 new Circle()

62
What happens in memory
  • There are 4 Circle objects in memory
  • Taking up a total of 416 64 bytes of memory

63
Consider the following code
  • public 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
  • v.add (new Circle())

These programs create 1 million Circle objects!
64
What happens in memory
  • There are 1 million Circle objects in memory
  • Taking up a total of 1,000,00016 16 Mb of
    memory


Note that the final PI field is repeated 1
million times
65
The use of static for fields
  • If a variable is static, then there is only ONE
    of that variable for ALL the objects
  • That variable is shared by all the objects

Total memory usage 16 bytes (112 doubles)
Total memory usage 8 Mb 8 bytes
(1,000,00011,000,001 doubles)
Total memory usage 40 bytes (415 doubles)
c1000000
c4

3.1415926536
PI
66
More on static fields
  • What does the following print
  • Note 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.3

Note you can refer to static fields
by object.variable
67
Even more on static fields
  • There is only one copy of a static field no
    matter how many objects are declared in memory
  • Even if there are zero objects declared!
  • The one field is common to all the objects
  • Static variables are called class variables
  • As there is one such variable for all the objects
    of the class
  • Whereas non-static variables are called instance
    variables
  • Thus, you can refer to a static field by using
    the class name
  • Circle.PI

68
Even even more on static fields
  • This 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)

69
Even even even more on static fields
  • Weve 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)

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

71
Hand Paintings
72
Back to our Circle class
  • public 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
73
Adding a method
  • public class Circle
  • double radius
  • final static double PI 3.1415926536
  • // Constructors...
  • double computeArea ()
  • return PIradiusradius

Note that a (non-static) method can use both
instance and class variables
74
Using that method
  • 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)

Prints 12.566370614356
75
What happens when that method is called
  • public class Circle
  • double radius
  • final static double PI 3.1415926536
  • public Circle()
  • radius 1.0
  • // other constructor
  • double computeArea ()
  • return PIradiusradius
  • public class CircleTest
  • public static void main (String args)
  • Circle c new Circle()

76
Review of our Circle class
  • public class Circle
  • double radius
  • final static double PI 3.1415926536
  • public Circle()
  • public Circle (double r)
  • radius r
  • double computeArea ()
  • return PIradiusradius

Slight change from before
77
A note about methods/variable order
  • Within a method, a variable must be declared
    before it is used
  • In a class, methods and variables can be declared
    in any order
  • This is different than C

78
End of lecture on 23 March 2007
79
Review of static for fields
  • If a variable is static, then there is only ONE
    of that variable for ALL the objects
  • That variable is shared by all the objects

Total memory usage 16 bytes (112 doubles)
Total memory usage 8 Mb 8 bytes
(1,000,00011,000,001 doubles)
Total memory usage 40 bytes (415 doubles)
c1000000
c4

3.1415926536
PI
80
Adding another method
  • double oneOverRadius()
  • return 1.0/radius
  • I couldnt think of a good reason to divide
    something by the radius

81
What happens now?
  • Code in class CircleTests main() method
  • Circle c new Circle() // c.radius is now 0.0
  • System.out.println (c.oneOverRadius())
  • Java wont crash, but many other programming
    languages (C and C, in particular) will
  • So well call this a crash for the sake of this
    lecture
  • Java prints Infinity
  • Not what we wanted, though!

82
One way to fix this
Note that the radius variable is now initialized
to 1.0
  • public class Circle
  • double radius 1.0
  • final static double PI 3.1415926536
  • // Constructors...
  • double computeArea ()
  • return PIradiusradius
  • double oneOverRadius()
  • return 1.0/radius

83
Back to our program
  • This code will now run properly
  • Circle c new Circle() // c.radius 1.0
  • System.out.println (c.oneOverRadius())
  • But this code will crash
  • Circle c new Circle() // c.radius 1.0
  • c.radius 0.0
  • System.out.println (c.oneOverRadius())

84
Where the crash occurs
  • public 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
PIradiusradius double oneOverRadius()
return 1.0/radius
Here is where the crash occurs
Here is the badly written code
85
Motivation for private fields
  • Problem 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 field
  • Give it private visibility
  • private means that only code within the class can
    modify the field

86
One way to fix this
Note that the radius variable is now private
  • public class Circle
  • private double radius 1.0
  • final static double PI 3.1415926536
  • // Constructors...
  • double computeArea ()
  • return PIradiusradius
  • double oneOverRadius()
  • return 1.0/radius

87
Todays demotivators
88
Back to our program
  • This code will now not compile
  • Circle c new Circle() // c.radius 1.0
  • c.radius 0.0
  • System.out.println (c.oneOverRadius())
  • Java will give a compile-time error
  • radius has private access in Circle

89
Back to our program
  • This code will also not compile
  • Circle c new Circle() // c.radius 1.0
  • System.out.println (c.radius)
  • Java will give the same compile-time error
  • radius has private access in Circle

90
The problem now
  • But 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

91
Our Circle class so far
  • public class Circle
  • private double radius 1.0
  • final static double PI 3.1415926536
  • // Constructors...
  • double computeArea ()
  • return PIradiusradius
  • double oneOverRadius()
  • return 1.0/radius
  • void setRadius (double r)
  • radius r
  • double getRadius ()

92
Using the get/set methods
  • public 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 PIradiusradius double
oneOverRadius() return 1.0/radius
void setRadius (double r) radius r
double getRadius () return radius

Here a method is invoked
Here the change to radius occurs
93
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
94
This problem is easily fixed
  • Change 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 mutators
  • To prevent changing the fields to a bad value
  • Well see another motivation in a bit

95
Visibilities in Java
  • There are four visibilities
  • private Only code within the same class can
    access the field or method
  • Note access means reading or writing the
    field, or invoking the method
  • public Any code, anywhere, can access the field
    or method
  • protected Used with inheritance
  • We wont get to that this semester
  • default Almost the same as public
  • This is the default (duh!)
  • Note that it cant be specified like the others
  • Also called package

96
A few notes on visibilities
  • You can NOT specify visibilities for method
    variables
  • Any method variable can only be accessed within
    that method
  • Think of it as public within the method (after
    its defined) and private outside the method
  • You can also specify visibilities for methods and
    classes
  • We will see this a bit in this course

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

98
DeCSS The program
  • include typedef unsigned int uint
    char ctb512"33733b2663236b763e7e362b6e2e667bd39
    3db0643034b96de9ed60b4e0e4\ 69b57175f82c787cf125a1
    a528fca8ac21fd999d10049094190d898d001480840913d7d3
    5246\ d2d65743c7c34256c2c6475dd9dd5044d0d4594dc9cd
    4054c0c449559195180c989c11058185\
    081c888c011d797df0247074f92da9ad20f4a0a429f53135b8
    6c383cb165e1e568bce8ec61bb\ 3f3bba6e3a3ebf6befeb6a
    beeaee6fb37773f2267276f723a7a322f6a2a627fb9f9b1a0e
    9a9e\ 1f0b8f8b0a1e8a8e0f15d1d5584cd8dc5145c1c5485c
    c8cc415bdfdb5a4edade5f4bcfcb4a5e\
    cace4f539793120692961703878302168286071b7f7bfa2e7a
    7eff2bafab2afeaaae2ff" typedef unsigned char
    ucharuint tb0115,0,1,2,3,4,0,1,2,3,4uchar
    FNULL uint lf0,lf1,outvoid ReadKey(uchar
    key)int ichar hst3 hst20if(F\
    NULL)Fmalloc(256)for(i0i2ihst1ctb2i1Fi\ strtol(hst,NULL,16)
    out0lf0(key116)(key\ 3lf10x7)0x8uchar Cipher(int sw1,\ int sw2)int
    i,a,b,x0,y0for(i0i2)(lf01
    6))1b((lf1\ 12)(lf120)(lf121)(lf124)
    )1lf0(lf01)\
    (a1)(bout(out8)xy void \ CSSdescramble(uchar
    sec,uchar key)uint iuchar endsec0x800uchar
    KEY5 for(i0iReadKey(KEY)sec0x80while(sec!\
    end)secFsecCipher(255,0)void
    CSStitlekey1(uchar key,uchar im) uchar
    k5int i ReadKey(im)for(i0ir(0,0)for(i9i0\ i--)keytb0i1ktb0i1
    Fkeytb0i1keytb0ivoid
    CSStitlekey2\ (uchar key,uchar im)uchar
    k5int iReadKey(im)for(i0iCipher(0,255)for(i9i0i--)keytb0i1ktb0
    i1Fkeytb0i1key\ tb0ivoid
    CSSdecrypttitlekey(uchar tkey,uchar dkey)int
    iuchar im16 uchar im260x51,0x67,0x67,0xc5,
    0xe0,0x00for(i0iCSStitlekey1(im1,im2)CSStitlekey2(tkey,im1)

99
DeCSS The shirt (and tie!)
100
DeCSS The poem
  • How to decrypt a
  • DVD in haiku form.
  • (Thanks, Prof. D. S. T.)
  • ------------------------
  • (I abandon my
  • exclusive rights to make or
  • perform copies of
  • this work, U. S. Code
  • Title Seventeen, section
  • One Hundred and Six.)
  • Muse! When we learned to
  • count, little did we know all
  • the things we could do
  • some day by shuffling
  • those numbers Pythagoras

Table 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 one hundred fifteen
fifty nine thirty eight ninety nine thirty
five one hundred seven one hundred eighteen
sixty two one hundred twenty six fifty four
forty three one hundred ten then
101
DeCSS The number
  • The worlds first illegal prime number
  • 4856507896573978293098418946942861377074420873513
    57924019652073668698513401047237446968797439926117
    51097377770102744752804905883138403754970998790965
    39552270117121570259746669932402268345966196060348
    51742497735846851885567457025712547499964821941846
    55710084119086259716947970799152004866709975923596
    06132072597379799361886063169144735883002453369727
    81813914797955513399949394882899846917836100182597
    89010316019618350343448956870538452085380458424156
    54824889333804747587112833959896852232544608408971
    11977127694120795862440547161321005006459820176961
    77180947811362200272344827224932325954723468800292
    77764979061481298404283457201463489685471690823547
    37835661972186224969431622716663939055430241564732
    92485524899122573946654862714048211713812438821771
    76029841255244647445055834628144883356319027253195
    90439283873764073916891257924055015620889787163375
    99910788708490815909754801928576845198859630532382
    34905580920329996032344711407760198471635311617130
    78576084862236370283570104961259568184678596533310
    07701799161467447254927283348691600064758591746278
    12126900735183092415301063028932956658436620008004
    76778967984382090797619859493646309380586336721469
    69597502796877120572499666698056145338207412031593
    37703099491527469183565937621022200681267982734457
    60938020304479122774980917955938387121000588766689
    25844870047077255249706044465212713040432118261010
    35911864766629638584950874484973734768614208805294
    43

102
DeCSS The images
103
DeCSS The recordings
  • All this info from http//www-2.cs.cmu.edu/dst/D
    eCSS/Gallery/
  • Or do a Google search for decss gallery

104
DeCSS The movie
105
Overriding methods (and constructors)
Creates a Circle of radius 1.0
  • Consider the following code
  • Circle c1 new Circle ()
  • Circle c2 new Circle (2.0)
  • Java knows which constructor to call by the list
    of parameters
  • This is called overloading
  • Meaning it means multiple things, depending on
    the context
  • Weve seen overloading before
  • 34 Performs integer addition
  • 3.04.0 Performs floating-point addition
  • 34 Performs string concatenation
  • The operator is overloaded

Creates a Circle of radius 2.0
106
Overriding methods (and constructors), take 2
  • The 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?
107
Using mutators in the constructor
  • Our 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)
108
Using mutators in the constructor
  • This 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)

109
Why we always use the mutators
  • Consider 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 ) radius 1.0 else radius r
diameter 2radius if ( radius size small else if ( radius size medium else if ( radius size large else size huge
110
End of lecture on 30 March 2007
111
Google April Fools Day Jokes (2007)
  • http//www.google.com/tisp/
  • http//mail.google.com/mail/help/paper/

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

113
An aside scoping issues
  • Consider 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 x
  • So this doesnt set the instance variable!
  • Instead, it sets the parameter equal to itself

114
An aside scoping issues
  • Lets modify that class
  • class Foo
  • int x 0
  • public Foo (int x)
  • this.x x
  • The this.x means the instance variable x
  • And the x means the parameter
  • Now this does the right thing
  • Another solution
  • class Foo
  • int x 0
  • public Foo (int y)
  • x y
  • By renaming the parameter, we achieve the same
    effect
  • This very relevant to HW 7!

115
Back to the static discussion
  • Remember 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
    object
  • In this example, it doesnt read/write the radius
  • In fact, that particular method doesnt care
    anything about the objects declared
  • Its only accessing a static field

116
Make getPI() static
  • Consider 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 object
  • Examples Math.sin(), Math.tan(), Math.cos()
  • They dont care about the state of any Math
    object
  • They only perform the computation

117
Invoking static methods
  • As 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

118
static methods and non-static fields
  • Consider 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())

119
What happening in memory
  • There are 4 Circle objects in memory
  • Which radius field does Circle.getRadius() want?
  • There are 1 million Circle objects in memory
  • There are no Circle objects in memory

c1000000
c4

3.1415926536
PI
120
The main static lesson
  • A 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!

121
static and non-static rules
  • Non-static fields and methods can ONLY be
    accessed by the object name
  • Static fields and methods can be accessed by
    EITHER the class name or the object name
  • Non-static methods can refer to BOTH static and
    non-static fields
  • Static methods can ONLY access static fields of
    the class they are part of

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

123
Very unofficial demotivators
124
Back to our main() method
Well learn about arrays in chapter 8
  • public static void main (String args)

The method does not return a value
Any code anywhere can call this method
  • Its a static method
  • Cant access non-static fields or methods
    directly
  • Can be called only by the class name

125
Implications of main() being static
  • It 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 object
  • Java assumes that it is in the same class

126
Another use of static methods
  • Lets say we want each Circle object to have a
    unique identifier
  • The 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 variable
  • static int lastAssignedID 0
  • Thus, for all Circle objects created, we will
    have a single lastAssignedID field

127
Circle ID numbers
  • We 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()

128
Todays demotivators
129
Debugging Java Code
130
Debugging Java code
  • In 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!
131
Program Demo
  • Errors/Main.java

132
What the error output means
  • The error output
  • Exception in thread "main" java.lang.NullPointerEx
    ception
  • at Error1.foo(Error1.java6)
  • at Main.main(Main.java4)
  • This means that
  • A null point exception happened
  • In the Error1.foo() method on line 6 of
    Error1.java
  • And 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()

133
Debugging Java code
  • In 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()

134
Program Demo
  • Errors/Main.java

135
What the error output means
  • The error output
  • Exception in thread "main" java.lang.NullPointerEx
    ception
  • at Error1.foo(Error1.java6)
  • at Error1.bar(Error1.java10)
  • at Main.main(Main.java5)
  • This means that
  • A null point exception happened
  • In the Error1.foo() method on line 6 of
    Error1.java
  • And that was called from Error1.bar() on line 10
    of Error.java
  • And that was called from Main.main() on line 5 of
    Main.java
  • Again, note that the top two lines tell the most
    useful information

136
Hondas best commercial
  • cog.mov

137
More on methods
138
Calling a method
  • Consider 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 of
  • The method works the same in both cases (returns
    the substring)
  • But it returns different results
  • Whenever we are calling a method, we also need to
    know which object we are calling it out of

139
Return values
  • Many methods return a value
  • Math.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

140
The return keyword
  • The return keyword does a few things
  • Immediately terminate the current method
  • Pass the value back to whoever called the method
  • You can have a return anywhere you want
  • Inside 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

141
More on returns
  • Consider 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?

142
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)
s
t
this
public String bar (String s) String t
CS 101 s return t
public String bar (String s) String t
CS 101 s return t
Foo() bar (String s) String
143
Returning an object from a method
  • We 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

144
Returning a non-object from a method
  • In other words, returning a primitive type from a
    method
  • public foo ()
  • // ...
  • return x y
  • This method evaluates xy, then returns that
    value to the caller

145
Chapter 2 Computer bugs
146
Off to arrays.
147
Yale vs. Harvard
148
Rational class
149
What weve seen so far
  • An example of creating a class
  • Car
  • Up next another example
  • Rational
  • Represents rational numbers
  • A rational number is any number that can be
    expressed as a fraction
  • Both the numerator and denominator must be
    integers!
  • Discussed in section 4.8 of the textbook

150
What properties should our Rational class have?
  • The numerator (top part of the fraction)
  • The denominator (bottom part of the fraction)
  • Not much else

151
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

152
Our first take at our Rational class
  • Our first take
  • public class Rational
  • private int numerator
  • private int denominator
  • //...
  • This does not represent a valid Rational number!
  • Why not?
  • Java initializes instance variables to zero
  • Both the numerator and denominator are thus set
    to zero
  • 0/0 is not a valid number!

153
Our next take at our Rational class
  • Our next take
  • public class Rational
  • private int numerator 0
  • private int denominator 1
  • //...
  • Weve defined the attributes of our class
  • Next up the behaviors

154
The default constructor
  • Ready?
  • public Rational()
  • Yawn!
  • Note that we could have initialized the instance
    variables here instead
  • The default constructor is called that because,
    if you dont specify ANY constructors, then Java
    includes one by default
  • Default constructors do not take parameters

155
The specific constructor
  • Called the specific constructor because it is one
    that the user specifies
  • They take one or more parameters
  • public Rational (int num, int denom)
  • setNumerator (num)
  • setDenominator (denom)
  • Note that the specific constructor calls the
    mutator methods instead of setting the instance
    variables directly
  • Well see why later

156
Accessor methods
  • Our two accessor methods
  • public int getNumerator ()
  • return numerator
  • public int getDenominator ()
  • return denominator

157
Mutator methods
  • Our two mutator methods
  • public void setNumerator (int towhat)
  • numerator towhat
  • public void setDenominator (int towhat)
  • denominator towhat

158
Rational addition
  • How to do Rational addition
  • Our add() method
  • public Rational add (Rational other)

159
The this keyword
Returns
160
The this keyword
  • this is a reference to whatever object we are
    currently in
  • Will not work in static methods
  • Well see why later
  • Note that the main() method is a static method
  • While were at it,
Write a Comment
User Comments (0)
About PowerShow.com