chapter 6 introduction to defining classes - … · 1 chapter 6 introduction to defining classes...
TRANSCRIPT
1
Chapter 6Introduction to Defining Classes
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Lambert / Osborne
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E222
Objectives
� Design and implement a simple class from user requirements.
� Organize a program in terms of a view class and a model class.
� Use visibility modifiers to make methods visible to clients and restrict access to data within a class.
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E333
Objectives (continued)
� Write appropriate mutator methods, accessor methods, and constructors for a class.
� Understand how parameters transmit data to methods.
� Use instance variables, local variables, and parameters appropriately.
� Organize a complex task in terms of helper methods.
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E444
Vocabulary
� accessor� actual parameter� behavior� constructor� encapsulation� formal parameter� helper method
� identity� Instantiation� lifetime� mutator� scope� state� visibility modifier
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E55
The Internal Structure of Classes and Objects
� An object is a runtime entity that contains data and responds to messages.
� A class is a software package or template that describes the characteristics of similar objects.– Instance variable declarations which define an
object’s data requirements.– Methods that define its behavior in response to
messages.
5
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E66
The Internal Structure of Classes and Objects (continued)
� Encapsulation: the combining of data and behavior into a single software package.
� Instantiation: The process of creating a new object.
6
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E77
The Internal Structure of Classes and Objects (continued)
� Classes, Objects, and Computer Memory:� When a Java program is executing, the
computer’s memory must hold:– All class templates in their compiled form.– Variables that refer to objects.– Objects as needed.
� Each method’s compiled byte code is stored in memory as part of its class’s template.
7
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E88
The Internal Structure of Classes and Objects (continued)
� Classes, Objects, and Computer Memory (cont):
� Memory for data is allocated within objects. � Although all class templates are in memory at all
times, individual objects come and go.– An object occupies memory with it is instantiated, and
disappears when no longer needed.– Garbage collection: the JVM process of keeping track of
which objects need to be stored and which can be deleted.
8
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E99
The Internal Structure of Classes and Objects (continued)
� Three Characteristics of an Object:� Behavior: defined by the methods of its class.� State: at any moment the instance variables
have particular values, which change in response to messages sent to the object.
� Identity: distinguish from other objects in memory, as handled by the JVM.
9
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E
The Internal Structure of Classes and Objects (continued)
� Three Characteristics of an Object (cont):� Of the variables, there can be none, one, or several.
– When there are none, the garbage collector purges the object from memory.
� Clients, Servers, and Interfaces:� Clients send messages.
– Only need to know the server’s interface.– Information hiding hides the server’s data
requirements and list of supported methods from clients.
10
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1111
A Student Class
� Using Student Objects:
� First, declare variables, then assign values to variables before using them.
� Mutators: messages that change an object’s state.
� Accessors: messages that access the object’s state. Used to see if a mutator works correctly.
11
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1212
A Student Class (continued)
� Implicit use of toString when a Studentobject is sent to a terminal window
12
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1313
A Student Class (continued)
� Objects, Assignment, and Aliasing:� An object can be assigned two variables. � At any time, it is possible to break the
connection to a variable and the object it references by assigning the null value to the variable.
13
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E
A Student Class (continued)
� How variables are affected by assignment statements
14
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1515
A Student Class (continued)
� Primitive Types, Reference Types, and the null Value:
� In Java, all types fall into two categories:– Primitive: 1 box that contains a value of primitive
type. � int , double , boolean , char , and longer and shorter
versions of these.
– Reference: a box that contains a pointer to an object.� String , Student , Scanner , and all classes.
15
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1616
A Student Class (continued)
� Primitive Types, Reference Types, and the null Value (cont):
� The difference between primitive and reference variables
16
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1717
A Student Class (continued)
� Primitive Types, Reference Types, and the null Value (cont):
� Can assign reference variables the null value.– If it pointed to an object, and
no other variable points to the object, the object’s memory goes to garbage collection.
17
The Student variable before and after it has been assigned the value null
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E1818
A Student Class (continued)
� Primitive Types, Reference Types, and the null Value (cont):
� Null pointer exception: when a program attempts to run a method with a null object.
18
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E
A Student Class (continued)
� The Structure of a Class Template:� All classes have a similar structure consisting
of 4 parts:– The class’s name and some modifying phrases.– A description of the instance variables.– One or more constructor method that indicates
how to initialize a new object.– One or more methods that specify how an object
responds to messages.
19
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2020
A Student Class (continued)
� The Structure of a Class Template (cont):� Class definitions: usually begin with the keyword
public .
� Class names: user-defined symbols that adhere to rules for naming variables and methods.
� Java organizes classes in a hierarchy.– Base: Object .
– Superclasses and subclasses.– Each class, except Object , can have one parent and
any number of children.20
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2121
A Student Class (continued)
� The Structure of a Class Template (cont):� Inheritance: a new class inherits the
characteristics of its superclass.– Extends the superclass by modifying and adding.
� Instance variables are nearly always private .� Visibility modifiers: private and public .
– Determine whether clients can see them.
21
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2222
A Student Class (continued)
� The Structure of a Class Template (cont):� When an object receives a message, it activates
the corresponding method, which manipulates the object’s data as represented by the instance variables.
� Constructors:� Purpose of a constructor is the initialize the
instance variables of a newly instantiated object.
22
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2323
A Student Class (continued)
� Constructors (cont):� Constructors are only ever activated when the
keyword new is used.
� A class template can have more than one constructor, as long as each has a unique parameter list.
� All constructors must have the same name as the class.
� Default constructors have empty parameter lists.23
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2424
A Student Class (continued)
� Constructors (cont):� A class is easier to use when it has a variety of
constructors.� Chaining Constructors:� Used when a class has several constructors.� Simplifies code by calling one constructor from
another:– This(<parameters>);
24
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2525
Editing, Compiling, and Testing the Student Class
� To use the Student class, save it in a file called Student.java and compile it.
� Once the Student class is compiled, applications can declare and manipulate Student objects if one of the following is true:– The code for the application and class are in the
same directory.– The class is part of a package.
25
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2626
Editing, Compiling, and Testing the Student Class (continued)
� Output from the TestStudent program
26
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2727
Editing, Compiling, and Testing the Student Class (continued)
� Finding the Location of Run-Time Errors:� The messages list the line and help trace the
errors in order to fix them.
27
Divide by zero run-time error message
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2828
The Structure and Behavior of Methods
� A method is a description of a task that is performed in response to a message.
� The Structure of a Method Definition:
� Use the visibility modifiers public and private to determine if the method is available to clients of the defining class.
28
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E2929
The Structure and Behavior of Methods (continued)
� The Structure of a Method Definition (cont):� The return type should be void when the method
returns no value.� Method names have the same syntax as other
Java identifiers.� Parentheses are required whether or not
parameters are present.– A parameter list, consists of one or more pairs of type
names and parameter names, separated by commas.
29
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3030
The Structure and Behavior of Methods (continued)
� The Structure of a Method Definition (cont):� Stub: a method whose implementing code is
omitted.– Stubs are used to set up incomplete but running
programs during program development.
� Return Statements:
� If a method has a return type, its implementing code must have at least one return statement that returns a value of that type.
30
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3131
The Structure and Behavior of Methods (continued)
� Formal and Actual Parameters:� Formal parameters are listed in a method’s
definition.� Actual parameters, or arguments, are values
passed to a method when it is invoked.� When a method has multiple parameters, the
caller must provide the right number and types of values.
31
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3232
The Structure and Behavior of Methods (continued)
� Parameters and Instance Variables:� The purpose of a parameter is to pass
information to a method.� The purpose of an instance variable is to
maintain information in an object.� Local Variables:� Used to provide temporary working storage for
data in a method.
32
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3333
The Structure and Behavior of Methods (continued)
� Helper Methods:� Breaks a complex task performed by a method
into subtasks.� Usually private, because only the methods in
the class need to use them.
33
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3434
Scope and Lifetime of Variables
� Scope of Variables:� The scope of a variable is that region of the
program within which the variable can validly appear in lines of code.
� A local variable is restricted to the body of the method that declares it.
� A private instance variable’s scope is the methods in its defining class.
34
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E
Scope and Lifetime of Variables (continued)
� Scope of Variables (cont):� Variables and their scope
35
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3636
Scope and Lifetime of Variables (continued)
� Block Scope:� Variables declared within (nested) any
compound statement enclosed in braces.� Lifetime of Variables:� The period during which it can be used.
– Local variables and formal parameters exist during a single execution of a method.
– Instance variables last for the lifetime of the object.
36
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3737
Scope and Lifetime of Variables (continued)
� Duplicating Variable Names:� The same name can be used for different
methods because the scope of a formal parameter or local variable is restricted to a single method.
� A local variable with the same name as an instance variable is said to shadow it.
37
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3838
Scope and Lifetime of Variables (continued)
� When to Use Instance Variables, Parameters, and Local Variables:
� Instance variable: to store information within an object.
� Parameter: to transmit information to a method.� Local variable: temporary working storage
within a method.
38
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E3939
Scope and Lifetime of Variables (continued)
� When to Use Instance Variables, Parameters, and Local Variables (cont):
� Common mistakes:– Instance variable used for temporary working
storage.– Local variable used to remember information as an
object.– Method accesses data by directly referencing an
instance variable instead of using a parameter.
39
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4040
Scope and Lifetime of Variables (continued)
� When to Use Instance Variables, Parameters, and Local Variables (cont):
� Reasons to prefer the use of parameters:– If several methods share a pool of variables and one
method misuses a variable, the other methods are affected.
– It is easier to understand methods and their relationships when defined by parameters and return values.
– Methods that are passed parameters can be reused in different situations.
40
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4141
Graphics and GUIs: Images, a CircleClass, and Mouse Events
� Loading Images from Files and Displaying Them:
� Some image file formats: JPEG, GIF, or PNG.� Once an image is available, a Java application
can load it into RAM for use.– ImageIcon image = new
ImageIcon(filename);
– Creates an ImageIcon object with a bitmap for the data in the image.
41
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4242
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Loading Images from Files and Displaying Them (cont):
� Example: program has a main application class that loads an image of a cat and passes the image to a new ColorPanel .
� The ColorPanel receives the image icon at instantiation and saves a reference in an instance variable.
� The ColorPanel maintains another object, an image, as part of its state.
42
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4343
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Geometric Shapes:� It is useful to implement each shape as a distinct
object with its own methods:– Allows users to manipulate attributes (color, size, etc.).– Allows more specific and complex shapes.– If a shape knows its own attributes, it just needs a
graphic context in order to display.– Easy for programs that use multiple shapes and designs.
43
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4444
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Defining a Circle Class:
� Circles have a color, center point, and radius.� Users can ask a circle to draw or fill itself, or if
a circle contains a given point (x,y).� Implementation of the Circle Class:
� The constructor receives the color, center point, and radius and assigns these values to instance variables.
44
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4545
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Using the Circle Class:� Displaying two Circle objects
45
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4646
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� The Method repaint:
� Used to refresh a GUI component, such as a panel.
� Example: move a shape to a new coordinate in response to a mouse click.
� Responses to Mouse Events:� Button presses and releases, mouse
movement, dragging, and mouse entry/exit.
46
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4747
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Responses to Mouse Events (cont):� Listener objects: attached to a panel, and used to
detect and respond to mouse events. � If a listener has a method whose parameter
matches the type of mouse event, the JVM runs the method and passes the event object to it as a parameter.
� The event object contains the mouse’s panel coordinates.
47
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4848
Graphics and GUIs: Images, a CircleClass, and Mouse Events (continued)
� Dragging Circles:� Example: the user selects a circle by pressing
the mouse, and moves it by dragging.� Uses three types of events and responses:
– Mouse press: saves the coordinates of the mouse.– Mouse release: deselects the shape and sets the
saved reference to null .
– Mouse drag: computes the x and y distances between the current and saved mouse coordinates.
48
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E4949
Summary
In this chapter, you learned:� Java class definitions consist of instance
variables, constructors, and methods.� Constructors initialize an object’s instance
variables when the object is created. A default constructor expects no parameters and sets the variables to reasonable default values. Other constructors expect parameters that allow clients to set up objects with specified data.
49
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E5050
Summary (continued)
50
� Mutator methods modify an object’s instance variables, whereas accessor methods merely allow clients to observe the values of these variables.
� The visibility modifier public is used to make methods visible to clients, whereas the visibility modifier private is used to encapsulate or restrict access to variables and methods.
� Helper methods are methods that are called from other methods in a class definition. They are usually declared to be private.
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E5151
Summary (continued)
51
� Variables within a class definition can be instance variables, local variables, or parameters. Instance variables are used to track the state of an object. Local variables are used for temporary working storage within a method. Parameters are used to transmit data to a method.
� A formal parameter appears in a method’s signature and is referenced in its code. An actual parameter is a value passed to a method when it is called. A method’s actual parameters must match its formal parameters in number, position, and type.
Ch
apte
r 6
Lambert / Osborne Fundamentals of Java 4E5252
Summary (continued)
52
� The scope of a variable is the area of program text within which it is visible. The scope of an instance variable is the entire class within which it is declared. The scope of a local variable or a parameter is the body of the method within which it is declared.
� The lifetime of a variable is the period of program execution during which its storage can be accessed. The lifetime of an instance variable is the same as the lifetime of a particular object. The lifetime of a local variable and a parameter is the time during which a particular call of a method is active.