1.objects - University of Hawaii

Download Report

Transcript 1.objects - University of Hawaii

USING OBJECTS
• What are Objects?
• Properties and Capabilities
• Classes and Instances
• Making Instances
• A Sample Program
Using Objects
1 of 32
© 2006 Pearson Education
What are Software Objects?
• Building blocks of software systems
– program is a collection of interacting objects
– objects cooperate to complete a task
• Objects model conceptual things
– meeting
– date
– to do this, they communicate by sending “messages” to each other
• Object model tangible things
–
–
–
–
school
car
____________________________
____________________________
• Objects model processes
– finding path through a maze
– sorting a deck of cards
• Objects have
– capabilities: what they can do, how they behave
– properties: features that describe the objects
Using Objects
2 of 32
© 2006 Pearson Education
Object Capabilities: Actions
• Objects have capabilities that allow them to perform actions
– objects are smart — they “know” how to do things
– an object gets something done only if some other object tells it to use
one of its capabilities
• Also called behaviors
Capabilities can be:
– constructors: establish initial state of object’s properties
– commands: change object’s properties
– queries: provide answers based on object’s properties
• Example: trash cans are capable of performing specific
actions
–
–
–
constructor: be created
commands: add trash, empty yourself
queries: reply whether lid is open or closed,
whether can is full or empty
Using Objects
3 of 32
© 2006 Pearson Education
Object Properties: State
• Properties determine how an object acts
– some properties may be constant, others variable
– properties themselves are objects — they also can receive messages
– trash can’s lid and trash are objects
Properties can be:
– attributes: things that help describe an object
– components: things that are “part of” an object
– associations: things an object knows about, but aren’t parts of the object
• State: all of object’s properties; changes if a property changes
– some don’t change, e.g., steering wheel of car
– others do, e.g., car’s color
• Example: properties of trash cans
–
–
–
attributes: color, material, smell
components: lid, container, trash bag
associations: a trash can can be associated with the room it’s in
Using Objects
4 of 32
© 2006 Pearson Education
Name that Object
• What are some capabilities of the objects in this room?
• What are some properties of the objects in this room?
• Which of these properties are attributes, which are
components and which are associations?
Using Objects
5 of 32
© 2006 Pearson Education
Classes and Instances
• Our current conception: each object corresponds directly to a
particular real-life object, e.g., a specific atom or automobile
• Disadvantage: too impractical to work with objects this way
– may be too many (i.e., modeling all atoms in the universe)
– do not want to describe each individual separately, because they may
have much in common
• Classifying objects factors out commonality
– among sets of similar objects
– lets us describe what is common once
– then “stamp out” any number of copies later
Imprints
(object instances)
Rubber stamp
(object class)
Using Objects
6 of 32
© 2006 Pearson Education
Object Classes
• Object class
– defines a category of objects
– defines capabilities common to a set of individual objects
• all trash cans can open, close, empty their trash
– defines properties that the objects have
• a property value of an individual object can be different from others
– defines template for making object instances
• particular trash cans
• each may have a metal casing, be blue, be a certain size, etc.
• Classes implement capabilities as methods
–
–
–
–
–
a method defines the response to a message
method is a sequence of statements in Java
each statement is a step in the response
objects cooperate by sending messages to others
each message “invokes a method”
• i.e., Java executes the sequence of statements in the method
• Classes implement a property as an instance variable
– slot of memory allocated to the object that can holds some value
– its value can be potentially changed
Using Objects
7 of 32
© 2006 Pearson Education
Object Instances
• Object instances are individual objects
– made from the class template
– one class may represent an indefinite number of object instances
– making an object instance is called instantiating that object
• Shorthand:
– class: object class
– instance: object instance (not to be confused with instance variable)
• Different instances of, say, TrashCan class may:
– have different color
– be at a different location
– have different trash inside
• So their instance variables can have different values
– note: object instances contain instance variables
• two different but related uses of the word instance
Using Objects
8 of 32
© 2006 Pearson Education
Object Instances (continued)
• Individual instances have individual identities
– this allows other objects to send messages to a specific object
– each is unique, even though it has same capabilities
– think of classroom full of students
• Note: in Java, the value of instance variable is always a
reference to an instance, not the instance itself
– unlike in other programming languages
• A reference is just the address in memory where the
properties of the instance are stored
– also called pointer
Properties
instancea
instancei
Using Objects
instanceb
9 of 32
© 2006 Pearson Education
Memory Revealed
• Every instance is stored in computer’s memory
– memory is a set of consecutively numbered storage locations, each
containing a byte
– instance is stored in contiguous bytes starting at a given location
• Instance is identified and referenced by unique address of its
starting location where it was created
– address looks like 0xeff8a9f4 (hexadecimal notation, base 16)
– just like postal address represents actual home
0x00000000
0x00000001
0x00000002
0x00000080
(vertical representation)
memory address
of instance 1
memory address
of instance 2
memory address
of instance 3
(horizontal representation of memory)
Using Objects
10 of 32
© 2006 Pearson Education
Messages for Object Communication
• No instance is an island — it must communicate with others to
accomplish task
– properties let it know about other objects whom it can talk with
• Instances send messages to one another to invoke a
capability (i.e., to execute a task)
– method is code that implements message
– we say “call a method” instead of “invoke capability”
• Each message requires:
–
–
–
–
sender: object initiating action
receiver: instance whose method is being called
message name: name of method being called
optionally parameters: more info telling method how to operate
• we’ll discuss parameters in detail in a few lectures
• Receiver can (but does not need to) send reply
– we’ll discuss return types in detail in a few lectures
Using Objects
11 of 32
© 2006 Pearson Education
Encapsulation
• Car encapsulates lots of information
– quite literally, under hood and behind dashboard
• So, you do not need to know how a car works just to use it
– steering wheel and gear shift are the interface
– engine, transmission, drive train, wheels, . . . , are the (hidden) implementation
• Likewise, you do not need to know how an object works to send
messages to it
• But, you do need to know what messages it understands (i.e., what
its capabilities are)
– class of instance determines what messages can be sent to it
Using Objects
12 of 32
© 2006 Pearson Education
Views of a Class
• Objects separate interface from implementation
– object is “black box”; hiding internal workings and parts
– interface protects implementation from misuse
Public Capability
Public Capability
Public Capability
Public Capability
Private
Properties
Public Capability
Public Capability
Note: private properties shown schematically as literally contained in an object. In reality,
they are actually stored elsewhere in memory and referenced by their addresses
• Interface: public view
– allows instances to cooperate with one another without knowing details
– is a contract: list of capabilities and documentation how to use them
• Implementation: private view
– properties that help capabilities complete their tasks
Using Objects
13 of 32
© 2006 Pearson Education
Notes About Java Syntax
• Reserved words
– certain words have a particular meaning in Java and cannot be used for
any other purpose
– case-sensitive (always all lower case)
class
public
new
private
extends
• Identifiers
– names used for classes, methods, and variables
– first character must be a letter or underscore
– rest may be any combination of letters, numbers, and underscores
• but no spaces
Professor
4thStreet
aPrettyLongName
a_pretty_long_name
Using Objects
14 of 32
© 2006 Pearson Education
Making Code More Readable
• Naming conventions
–
–
–
–
suggestions how to name things
they are intended to make code easier to read and understand
add consistency to a program
not enforced by compiler
• We use capitalization to distinguish an identifier’s purpose
– class names begin with upper case
– method and variable names begin with lower case
– in the book, instance variables start with an underscore
• this is not common, and we discourage it because it's less readable
• different programmers have different programming style
• Use a name that represents the functionality of an object
Good Name
Poor Name
Professor
Thing (no role, purpose)
method:
teachClass
doStuff (not specific)
instance:
professor
p (too cryptic)
class:
Using Objects
15 of 32
© 2006 Pearson Education
A Complete Program
• Here is our first complete Java program:
public class BallApplication extends wheels.users.Frame {
public BallApplication () {
new Demos.Bounce.BouncingBall ();
}
public static void main (String [] arguments) {
new BallApplication ();
}
}
• We will deconstruct this code
• Let’s see the demo!
Using Objects
16 of 32
© 2006 Pearson Education
Syntax: Declaring a Class
• Class declaration tells Java that we define a new class
– i.e., we are “declaring” our intent to “define” class that can be used as a template to
instantiate object instances
– program must include at least one class definition
public class BallApplication extends wheels.users.Frame
• Reserved word public means that anyone can create instance of the
class
• Reserved word class means that we define a new class
• BallApplication is name of the class
– named because it is an application (or program) with a bouncing ball
• extends wheels.users.Frame means:
– there is a class wheels.users.Frame defined in the users subpackage of package
wheels (explained later)
• an object of class Frame displays a window and a “Quit” button
– our class extends the functionality of Frame
– in this case, we add the ability to create a bouncing ball to the Frame class
• our application displays a window with a bouncing ball and a “Quit” button
Using Objects
17 of 32
© 2006 Pearson Education
Syntax: Defining a Class
• Class definition following declaration tells Java compiler how to
make instances of this class and how those instances respond to
messages
–
–
–
–
thus, simply declaring class not enough
we must also define what class does (i.e., how it will fulfill its purpose)
Java code is like dictionary: “declaration” of concept, then its definition
no code can appear outside of a class definition
• Curly braces {} indicate beginning and end of logical block of code;
the “code body” — in this case, class definition
– separate declaration from definition
– code written between curly braces is belongs to class declared in front of them
public class BallApplication extends wheels.users.Frame {
}
– this is an example of empty code block — “no” code is legal, i.e., syntactically correct, and
therefore compiles, but does not do anything useful
• Java programs are composed of arbitrarily many classes
Using Objects
18 of 32
© 2006 Pearson Education
Constructors
• Next we need instances of our classes to do something useful
• Constructor is special method that is called whenever the class is
instantiated (it creates the instance)
–
–
–
–
another object sends a message that calls constructor
constructor is the first message an object receives
this object cannot receive a constructor message again
establishes initial state of properties of the instance
• If class doesn't define any constructors, Java makes one for you
– called default constructor
– initializes all instance variables for instance to their default values
• We need to write our own constructor...
– when our application is created we want to create new object (that bounces
around on the screen!)
Using Objects
19 of 32
© 2006 Pearson Education
Syntax: Declaring Constructors
• We want to declare constructor for our class:
public class BallApplication extends wheels.users.Frame {
public BallApplication () {
}
}
• This is our first example of method declaration
– declares to compiler our intent to define method that implements response to particular message;
in this case create a new object of this class
• General syntax notes:
– public means any other object can call this constructor
– BallApplication is method’s name
– parentheses () indicate that this method doesn't need parameters (explained later)
• Constructors have special syntax:
– must always have same name as class name
• Notice: constructor is inside the curly braces of class body
– so constructor is a special capability of the class
Using Objects
20 of 32
© 2006 Pearson Education
Introducing Packages
• What does class BallApplication need to fulfill its purpose?
• Ball which bounces around screen!
• This has already been written for you
– built by someone else, but usable by anyone
– like parts in a catalog
– package is a Java catalog
• Packages are collections of related classes
– library of reusable classes (demos, wheels)
• Packages can also contain other packages
– “nesting” provides better organization
– like sections and sub-sections in catalog
• Packages are reflected in the file system
– file with the class must have the name of the class and suffix “.java”
– it must be inside a folder whose name is the package name
– folder that corresponds to subpackage must be inside a folder whose name is the name of
the enclosing package
• Always have classes in a package!
Using Objects
21 of 32
© 2006 Pearson Education
More Packages
• To access classes in another package, must “qualify” class name by
package(s) it is in
– prepend each package name, separated by periods
wheels.users.Frame
package
names
class
name
– Frame is a class in package users, which is a subpackage of wheels
• Instead of having to qualify class names we can import them
import wheels.users.Frame;
• We can also import all classes in a package using “*”
import wheels.users.*;
• Imports follow package declaration
• Unlike the book, we encourage importing classes
– it makes code simpler, more readable
– it makes statements shorter, often eliminates wrapping onto next line
Using Objects
22 of 32
© 2006 Pearson Education
Object Instantiation
• Object instantiation creates an object instance from a particular class
–
–
other instances can then send messages to the new instance
constructor is first message: makes the instance
public class BallApplication extends wheels.users.Frame {
public BallApplication () {
new demos.bounce.BouncingBall();
}
}
• Reserved word new tells Java to make new object instance, it “calls”
constructor
–
–
name of constructor follows new; since constructors have same name as their classes, this defines the class to
instantiate
e.g., new BouncingBall is created (class in bounce package which is a subpackage of demos)
• When new object is made Java
executes statements defined in constructor
• Result of calling constructor is new instance of that class
–
•
example of a message that returns a value
We don’t keep track of BouncingBall because we don’t need to call any of its methods
–
–
in most cases we need to call methods of new objects so that we must keep track of them
later we will show how
Using Objects
23 of 32
© 2006 Pearson Education
What about the rest?
public static void main(String[] arguments) {
new BallApplication();
}
• To run the program, something must create an instance of class
BallApplication
– the Java Virtual Machine (JavaVM) starts the program by calling the special method main
– Our main() method then creates an instance of class BallApplication
• You can think of main() as prologue to application’s constructor
–
–
–
–
special method that can be called without referring to an object
it just gets called and then constructs your application
Every program MUST have one… it’s your starting point!
it’s a lot of magic! (for now)
• BallApplication object is the first thing created when the
program is run
– for now we use wheels.users.Frame, later use something that does less work
Using Objects
24 of 32
© 2006 Pearson Education
More about Frames
• Frames magically do a lot of work for you
– handle input stream of events, i.e., mouse clicks and keyboard presses
– send messages to appropriate GUI component to handle event
Input
from
user
Using Objects
wheels.users.Frame
25 of 32
Appropriate GUI
component
(button, menu, etc.)
© 2006 Pearson Education
Syntax: Extending Frame Class
• To create your special frame, you don’t need to start from
scratch (which would be a huge amount of work) - instead you
can extend, i.e., add to, a default frame defined already
– you can take advantage of the work default frames do for you
• Syntax for declaring extension is simple:
public class BallApplication extends wheels.users.Frame
• Three types of packages help you write your programs:
– demos: Demos Package — library to illustrate examples in lectures
– wheels: graphics library used by examples in the book
– Sun provides many more packages with JAVA
•
•
•
•
•
•
GUI (graphical user interfaces)
databases
networking and communication
2D graphics
sound
etc., etc.
Using Objects
26 of 32
© 2006 Pearson Education
Steps of Execution
• Java programs are executed by the Java VM
–
–
–
–
your computer is the real machine (Mac, PC)
Java defines its common one on top of all real machines
Java VM is the same for all types of computers
you can compile Java classes on one computer and execute it on another
• What’s going on inside Java VM when we start with
main()?
public static void main(String[] arguments)
inside main()
new BallApplication();
inside BallApplication()
new Demos.Bounce.BoucingBall();
What about static, void, String[] and arguments?
– we’ll talk about them later
– for now, just accept that it’s needed to start your program
Using Objects
27 of 32
© 2006 Pearson Education
Final Code for BallApplication
• Now that we have deconstructed it, let’s look at this code one
more time:
public class BallApplication extends wheels.users.Frame {
public BallApplication() {
new demos.bounce.BouncingBall();
}
public static void main(String[] arguments) {
new BallApplication()
}
}
Using Objects
28 of 32
© 2006 Pearson Education
BallApplication (cont.)
• Execution Steps
– user starts program
• in Eclipse, by right-clicking BallApplication and selecting “Run”
command from popup menu
• this executes BallApplication (on a PC)
– method main() is called by JavaVM
– BallApplication is instantiated by the new command
– constructor BallApplication() is called
– BouncingBall is instantiated by the new command
– constructor BouncingBall() is called, it starts bouncing
– BallApplication’s constructor is now finished, BallApplication and
anything constructed in it keep running, e.g., BouncingBall keeps
bouncing
– user quits the application by clicking the “Quit” button
– BallApplication is destroyed and BouncingBall with it
Using Objects
29 of 32
© 2006 Pearson Education
Conclusion
• Interface for bouncing ball is extremely simple — instantiate it
and watch it go
– pro: it is easy (it does all the work!)
– con: it is not possible to change anything about the ball
– class interfaces can be this simple or much, much more complex
Using Objects
30 of 32
© 2006 Pearson Education