Lecture 6: Defining your own Classes - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Lecture 6: Defining your own Classes

Description:

The basketball has color and lines now! How would you write this? How would ... 2 Lines. 2 Arcs (these are new) You'd have to ... your clothes are ... – PowerPoint PPT presentation

Number of Views:19
Avg rating:3.0/5.0
Slides: 51
Provided by: andream2
Category:

less

Transcript and Presenter's Notes

Title: Lecture 6: Defining your own Classes


1
Lecture 6 Defining your own Classes
2
Last time
  • We finished up conditionals

if (hoop.contains(point)) score score 2
if (hoop.contains(point)) baskets baskets
1 else misses misses 1
3
Last time
  • We learned about booleans
  • We learned how to use these to make onMouseDrag()
    a bit more clean and efficient

boolean carryingBall public void
onMousePress(Location point) carryingBall
ball.contains(point) public void
onMouseDrag(Location point) if (carryingBall)
//do something
4
Conditional assignment to booleans
  • How can you make this code simpler?

if (ball.contains(point)) carryingBall
true else carryingBall false
5
Conditional assignment to booleans
  • How can you make this code simpler?
  • Like this (we just saw it)

if (ball.contains(point)) carryingBall
true else carryingBall false
carryingBall ball.contains(point)
6
Conditional assignment to booleans
  • How about this code?
  • Theres a subtle difference

if (ball.contains(point)) missedBall
false else missedBall true
7
Conditional assignment to booleans
  • How about this code?
  • Theres a subtle difference
  • If you see true false reversed in an if/else,
    just use not (!)

if (ball.contains(point)) missedBall
false else missedBall true
missedBall !ball.contains(point)
8
Some notes on style
  • 2 styles tyically used for braces

public void begin() if (condition) //do
something else //do something else
public void begin() if (condition) //do
something else //do something else
9
Some notes on style
  • Weve seen 4 kinds of names so far
  • Class names
  • Starts with capital
  • Camel-case
  • Method names
  • Starts with lowercase
  • Camel-case

FilledRect, NoClicking, FramedOval
onMouseClick(), begin(), onMouseDrag()
10
Some notes on style
  • Variable names
  • Same as method names
  • Distinguishable by parentheses after method call
    or declaration
  • Constant names
  • All caps
  • Words separated by underscores

someInt, myVariable, numberOfHits, myRectangle
SWATCH_LOCATION, BOX_WIDTH, BOX_LEFT, BOX_RIGHT
11
Some notes on style
  • Comments
  • Typically go above or to the side of what youre
    talking about

/ Oval to represent the basketball.
/ FilledOval ball
FilledOval ball //Oval to represent the
basketball
// This method draws a sign and initializes
instance variables public void begin()
12
Basketball
  • Were going to keep using our basketball game
  • This time, though, Ive made it more realistic
  • The basketball has color and lines now!
  • How would you write this?
  • How would you move the ball?

13
Basketball
  • You could use 6 instance variables
  • 1 FilledOval
  • 1 FramedOval
  • 2 Lines
  • 2 Arcs (these are new)
  • Youd have to construct all 6 in begin()
  • Youd have to move all 6 in onMouseDrag()
  • Any ideas for a better way?

14
Basketball
// program that displays how many times the mouse
has been clicked public class Basketball extends
WindowController private FramedOval
hoop // the oval that represent the hoop
private BBall ball // this is the ball
public void begin() ball new
BBall( BALLX, BALLY, BALLSIZE, canvas)
// Move the ball public void
onMouseDrag(Location point) if (
ball.contains(lastMouse) )
ball.move( point.getX() - lastMouse.getX(),
point.getY() - lastMouse.getY()
) lastMouse point
// increment the counter and
update the text public void
onMouseRelease(Location point) if
( hoop.contains(point) ball.contains(lastMouse)
) score score 2
display.setText("Your score is " score
) ball.moveTo(BALLX,B
ALLY)
  • Look at the code for the new Basketball program
  • at left is the code w/some things omitted)
  • Just the code for the ball
  • Instead of 6 instance variables, it has just one!
  • Variable is of type BBall

15
Whats BBall?
  • Its a basketball
  • Is that part of objectdraw?
  • No!
  • We wrote it ourselves
  • Somehow, in Java, we can make new classes of
    objects
  • These can be designed to fit the program were
    writing.

16
Basics of classes
  • Youve already been writing classes
  • And, you know the basics of what a class needs
  • Remember the robot from the first day of class?
  • A class describes a part of the robot
  • Methods describe things you can tell it to do

public class Name constant and variable
declarations methods
17
WindowController
  • How do our classes so far fit the robot part
    model?
  • Youve been writing classes that respond to mouse
    actions
  • Mouse actions were the methods
  • You told your classes how to behave when they
    received mouse clicks, drags, etc.
  • Who calls these methods?
  • The system knows when you extend WindowController
    that it should call them
  • It calls them when the user does things with the
    mouse.

18
BBall
  • BBall isnt going to extend WindowController
  • With BBall, were not describing mouse events
  • Were writing methods to describe things we want
    to tell our basketball
  • e.g. move moveTo
  • Not onMouseClick, onMouseDrag, etc

public class BBall Location position
//instance variable public void move(int dx,
int dy) //method telling how to move a BBall

19
Whats in a BBall?
  • Classes need
  • Whatever instance variables are necessary to
    describe the parts of an object of the class
  • BBall is made up of ovals, arcs, lines so its
    instance vars will be circles, arcs, and lines.
  • A special method called a constructor
  • Youve used these (with new), you just havent
    written one
  • Constructor sets up the parts of the object
  • Builds the instance vars
  • Methods
  • Statements describing how to do what we want the
    object to do

20
Whats in a BBall?
  • Lets look at the BBall code

21
Constructors
  • These perform actions that must be undertaken
    when an object is created
  • Similar to begin()
  • Provide initial values of instance variables
  • Create graphic objects
  • To declare a constructor
  • Name is the same as that of the class it belongs
    to
  • No void before methods name here
  • Constructor needs no type -- it builds an object
    of the classs type!

public ClassName(params )
22
Constructors
  • Heres the BBall constructor declaration
  • Has parameters for
  • starting location of upper left part of ball
  • Size of basketball
  • The canvas
  • The type DrawingWindow is new
  • This is the type of the canvas weve been using
  • Need canvas for all the graphical object
    constructors
  • FilledRect, FramedRect, etc

public BBall(double left, double top, double
size, DrawingCanvas aCanvas)
23
Constructors
  • Heres the BBall constructor declaration
  • To call this, you would just use new
  • Exactly the way weve been doing it with the
    graphics objects

public BBall(double left, double top, double
size, DrawingCanvas aCanvas)
new BBall(50, 50, 60, canvas)
24
Mutator Methods
public void methodName(ParameterType parameter,
...) . . .
  • First keyword in a method header is public or
    private
  • Determines visibility
  • public methods can be used by other classes
  • private methods can only be used by their own
    class
  • You couldnt call setColor() on the FilledRect if
    it wasnt public
  • If it was private, the compiler wouldnt let you
    run this
  • Youre calling FilledRects setColor() from
    NoClicking

public class NoClicking public void begin()
myRect new FramedRect(100, 100, 200, 200,
canvas) myRect.setColor(Color.yellow)
25
Visibility
public void methodName(ParameterType parameter,
...) . . .
  • Your methods are usually public (so far)
  • In contrast, we always make instance variables
    private
  • This is so that theyre not accessible to other
    classes
  • Cant alter BBalls internals from outside BBall
  • Having private instance variables guarantees that
    the only way someone can change your object is
    through its methods, in the way you specify

private Text textBox
26
Mutator Methods
  • Second keyword in methods header is void
  • Indicates that this is a mutator method
  • That it just does a task rather than returning a
    value
  • Third part of method header is the methods name
  • This is your choice!
  • Weve been using special names so far
    (onMouseClick, etc)
  • You can make your own classes have methods called
    anything

public void methodName(ParameterType parameter,
...) . . .
public void methodName(ParameterType parameter,
...) . . .
27
Mutator Methods
  • Last thing in a method header are formal
    parameters
  • This is a specification of what you have to call
    the method with
  • So far weve seen methods that require one piece
    of info
  • The Location, point, is determined by the system
    based on where the mouse is, and then the system
    calls onMouseClick() and passes point in
  • Formal parameters are very similar to variable
    declarations

public void methodName(ParameterType paramName,
...) . . .
public void onMouseClick(Location point) . . .
28
Mutator Methods
  • You can make method headers that require more
    than one piece of information
  • Just use more than one formal parameter
  • You can then call these methods with
    appropriately typed actual parameters
  • We declare that move takes 2 doubles, xOffset and
    yOffset
  • We can then call it with 2 doubles (55 and 70)

public void move(double xOffset, double yOffset)
ball.move(55, 70)
29
Accessor Methods
  • Weve seen accessor methods in use
  • But we havent dclared them or seen their headers
  • Heres contains(), from the BBall class
  • Instead of void, theres a type now!
  • In this case its boolean its what the method
    returns
  • Call this the return type
  • Result of sending this message to an object will
    be a value or either true or false
  • void just means a method has no return type
  • So void is a type its just no type

ball.getX() ball.contains(point)
public boolean contains(Location point)
30
Accessor Methods
  • Heres the entire contains method from BBall
  • So what does this method do?
  • Says that to test if a BBall contains a point,
    just test if its body (the main filledOval)
    contains the point
  • So it tests the body and returns whatever that
    result was
  • Something else new here the return statement
  • Tells Java what value to return

public boolean contains(Location point) return
body.contains(point)
31
Return Statement
  • Heres the entire contains method from BBall
  • Return statement is used only in non-void methods
  • Use it like this
  • return expression
  • Value produced by expression must be same type as
    methods return type
  • See above theyre both boolean

public boolean contains(Location point) return
body.contains(point)
32
Return Statement
  • What if you wanted to get the size of a BBall?
  • Write a method to do it!
  • Above methods return type is int
  • The expression after the return statement is
    body.getWidth()
  • This is also of type int
  • This would be an error (and nonsensical!)

public int getSize() return body.getWidth()
public int getSize() return body.getColor()
33
Return Statement
  • Accessor methods have to have at least one return
    statement
  • This is so that the expressions that use calls to
    accessor methods are guaranteed to have a value
  • You could have multiple return statements
  • Just make sure every possible path through the
    method leads to a return statement

public int getSize() if (isInflated)
return 30 else return 10
34
Talking to yourself
  • Sometimes we might want an object to send a
    message to itself
  • Why?
  • Look at move() in BBall
  • This has 6 statements to move all the parts of
    the ball

// move the ball by specified offsets public
void move( double dx, double dy) // move
each part of the ball by the offsets provided
body.move(dx,dy) border.move(dx,dy)
vert.move(dx,dy) horiz.move(dx,dy)
leftCut.move(dx,dy) rightCut.move(dx,dy)

35
Talking to yourself
  • How would you implement moveTo()?
  • You could write it with 6 statements, just like
    move()
  • One to move each piece of the ball to the new
    location
  • Or you could just figure out how far you need to
    move, then call move()

public void moveTo( double x, double y)
//do something
public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location this.move ( x -
body.getX(), y - body.getY() )
36
Talking to yourself
public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location this.move ( x -
body.getX(), y - body.getY() )
  • What happened there?
  • This part computes the difference between the
    point to move to and the balls current location
    (i.e. how far to move)
  • This part just calls move() on this ball
  • i.e.the same ball that moveTo() was called on
  • Tells itself to move the distance we computed

x - body.getX() y - body.getY()
this.move ( x - body.getX(), y -
body.getY() )
37
Talking to yourself
public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location this.move ( x -
body.getX(), y - body.getY() )
  • this is a special keyword in Java
  • If you use this in a method, it refers to the
    object that the method was called on
  • If you say
  • Then while moveTo() is running, any this inside
    moveTo refers to ball
  • Here, the this in moveTo() would refer to
    otherBall

ball.moveTo(5, 6)
otherBall.moveTo(3, 45)
38
Talking to yourself
public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location this.move ( x -
body.getX(), y - body.getY() )
  • The above version of moveTo() is a lot shorter
    and easier to understand than if we wrote all 6
    statements
  • Also, if you added another piece to the ball, you
    wouldnt have to change moveTo()
  • Say the ball has a UNC logo on it
  • You only have to add an extra move() statement in
    move()
  • moveTo will still work as written!

public void move( double dx, double dy)
body.move(dx,dy) border.move(dx,dy)
vert.move(dx,dy) horiz.move(dx,dy)
leftCut.move(dx,dy) rightCut.move(dx,dy)
logo.move(dx, dy)
39
Talking to yourself
public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location this.move ( x -
body.getX(), y - body.getY() )
  • Its pretty common to talk to yourself in Java
  • So much so that Java tries to make it easy for
    you
  • If you call a method and leave out the object on
    which to call it, Java will assume you meant this
  • You could thus write moveTo like this
  • Your choice which to use whichever makes more
    sense to you

public void moveTo( double x, double y )
// move the ball by the offsets needed to
reach desired location move ( x -
body.getX(), y - body.getY() )
40
Another example
  • Lets look at another custom graphics object
  • The T-shirt
  • This could be used to soup up your laundry
    program
  • You could have shirts that look like shirts!
  • Currently, all your clothes are square
  • Not exactly a fashion statement, or at least not
    the one you wanted to make

41
T-Shirts
  • TShirt is kind of like BBall
  • It draws an object composed of six subpieces
  • Its constructor creates all the subpieces and
    associates names with them
  • Its move method moves them all
  • Its moveTo method depends on its move method.

42
T-Shirts
  • There are also a few differences
  • TShirts contains method can not just call the
    contains method of one other object
  • It has some extra methods (setColor,
    sendToFront).
  • You could pretty easily put this in your laundry
    program instead of a FilledRect
  • Maybe just change the type

43
Custom Classes
  • Youve seen move() and moveTo() on rectangles and
    other shapes
  • Hopefully this makes it easy to understand the
    idea of defining your own methods in a new class
  • You shouldnt think that you can only define
    methods like the existing ones
  • You should design methods that are appropriate
    for the role of the object in your program

44
Back to the Robot
  • Robot might be one object
  • made up of FilledRects for the arms, legs, body,
    and head
  • Or, he might have custom Leg, Arm, Body, and Head
    objects!
  • Each could have methods
  • leg.move()
  • arm.grab()

45
Custom Classes
  • You might also want a totally new method on BBall
  • In our program, the ball always has to reset to
    the starting point
  • How about a reset() method?
  • This would put the ball back in its initial
    position

46
Adding reset() to BBall
  • How would you add reset() to BBall?
  • What instance variables would you need?
  • How would you change the constructor?
  • What would the reset() method look like?

47
Adding reset() to BBall
  • How would you add reset() to BBall?
  • What instance variables would you need?
  • How would you change the constructor?
  • What would the reset() method look like?

double initX, initY
48
Adding reset() to BBall
  • How would you add reset() to BBall?
  • What instance variables would you need?
  • How would you change the constructor?
  • What would the reset() method look like?

double initX, initY
initX top initY left
49
Adding reset() to BBall
  • How would you add reset() to BBall?
  • What instance variables would you need?
  • How would you change the constructor?
  • What would the reset() mutator method look like?

double initX, initY
initX top initY left
public void reset() this.moveTo(initX,
initY)
50
Adding reset() to BBall
  • Now you can just change onMouseRelease() to call
    reset(), in the class that extends
    WindowController
  • Before
  • After

public void onMouseRelease(Location
point) if ( hoop.contains(point)
ball.contains(lastMouse) )
score score 2
display.setText("Your score is " score )
ball.moveTo(BALLX,BALLY)

public void onMouseRelease(Location
point) if ( hoop.contains(point)
ball.contains(lastMouse) )
score score 2
display.setText("Your score is " score )
ball.reset()
Write a Comment
User Comments (0)
About PowerShow.com