Student Responsibilities Mat 2170 Week 10

Transcription

Student Responsibilities Mat 2170 Week 10
Student Responsibilities
Mat 2170
Week 10
Reading: Textbook, Chapter 6, Chapter 7.1 – 7.3
Classes and Objects
Lab: Inheritance
Mathematics and Computer Science Department
Eastern Illinois University
Attendance
Fall 2008
2
1
The javadoc Documentation System
Sample javadoc Pages — RandomGenerator
One of the important ways in which Java works together with the
World–Wide–Web is in the design of its documentation system,
javadoc.
The javadoc program reads Java source files and generates
documentation for each class in the file.
Complete documentation for the ACM Java Libraries is located at:
http://jtf.acm.org/javadoc/student/
3
4
Constructor and Method Summaries
5
Constructor and Method Details
6
7
8
Writing javadoc Comments
Documentation Comments
Documentation comments begin with /** and end with */.
The javadoc program from the Java developer’s kit (JDK)
produces nicely formatted HTML documentation from special
comments embedded in the source code.
Lines that begin with @ are tags that have special meaning.
@author
To make this work with your own programs, you need to add
specially formatted comments to your code.
@param
@return
A javadoc comment begins with the characters /** and extends
up to the closing */ just as a regular comment does.
Starts a paragraph where one or more author
names may be entered
Starts a parameter description for a function parameter with the given name
Starts a return value description for a function
Java defines a few more tags and it is possible to define your own.
However, you only need to know the above tags for now.
Using documentation comments helps programmers produce
actuate and consistent documentation.
Note you can also add html formatting to your documentation
comments.
10
9
Documentation Comments: Examples
Java Classes
/**
* Moves the GMovingSquare according to the current
* displacement.
*/
public void move()
Class: a collection of (usually related) data, along with the
methods or operations capable of accessing it
/**
* Returns a copy of the current displacement (velocity) of
* the GMovingSquare.
* @return a copy of the current velocity
*/
public GPoint getDisplacement()
11
/**
* Sets the displacement (velocity) of the GMovingSquare to
* be (x,y).
* @param x the x component of the new displacement
* @param y the y component of the new displacement
*/
public void setDisplacement(double x, double y)
Data members: the storage components of a class
Member functions: the messages or methods of a class, used to
access and modify the data members
Must declare (instantiate) an object of the class before allowed to
store data in it or send it a message
12
Java Objects
Defining Our Own Classes
The standard form of a class definition in Java:
Fundamental Data Types
Examples: int, double, boolean
public class name extends superclass
{
class body
}
Objects of a fundamental type have:
1
a state described by a single value.
Java Classes
The extends clause on the header line specifies the name of the
superclass.
Examples: String, GRect, GPoint
Objects of a class have:
1
a state: a collection of values or attributes
2
messages which the object understands and can act upon
13
If the extends clause is missing, the new class becomes a direct
subclass of Object, which is the root of Java’s class hierarchy.
14
Class Contents
Creating Classes
The body of a class consists of a collection of Java definitions that
are generically called called entries.
We can design exactly the structure needed to store related data
The most common entries are:
We learned how to use classes, now we’ll learn how to modify
them, and create our own by:
We can designate exactly how data may be accessed or modified
1
constructors — how to create an instance (an object with initial
value/s)
2
methods — the methods associated with the class
adding attributes / data to existing classes
3
instance variables — any necessary local objects
overriding messages in existing classes
4
named constants — any necessary constants for the class
building a class from “scratch”
15
adding messages to existing classes
16
Thinking about clocks. . .
Thinking about clocks. . .
A Wall clock is a kind of clock
⇒ a clock that hangs on a wall
An Alarm clock is a kind of clock
⇒ a clock with an alarm
A Wall Clock. . .
A Grandfather clock is a kind of clock
⇒ a clock with a pendulum and chimes
An Alarm Clock. . .
A Wristwatch is a kind of clock
⇒ a clock that straps to your arm
Wall clocks, Alarm clocks, Grandfather clocks, and Wristwatches are
specialized clocks
A Grandfather Clock. . .
17
A Wristwatch. . .
18
Inheritance Hierarchy
Extending Classes
Wouldn’t it be nice to be able to create specialized program
objects without starting from scratch?
Clock
For example:
Blinking rectangles
IS−A relationships
Moving circles
Arbitrary precision numbers
Wall Clock
Alarm Clock Grandfather
Clock
Inheritance is the object–oriented programming mechanism for
specialization.
Wristwatch
19
20
Inheritance
Derived Classes
A derived class IS–A version of its parent class.
Inheritance is the ability to define new classes of objects using
existing classes as a basis.
It has the same members its parent class has.
It can add members — both methods and data
The new class inherits the attributes and behaviors of the parent
classes.
It can re–define members of the parent class, over-riding the
parent’s definition.
The new class IS–A specialized version of the parent class.
21
For example, re-defining what it means to move() by giving a new
implementation for the function.
22
Inheritance
Class Message Examples
Constructors: Create an object, provide initial values
GRect rect = new GRect(0.0, 0.0, 20.0, 30.0);
A natural way to reuse code
Programming by extension rather than re-invention
Mutators: Change the state or attributes
MyCircle.setColor(Color.RED);
Object-oriented paradigm is well–suited for this style of
programming
Inspectors: Determine something about the state
double bh = Box.getHeight()
Terminology
Parent, base, or superclass
Facilitators: Perform a task
MyCircle.move();
Derived or subclass
23
24
Derived Class Definition
A Square and More. . .
is-a
A GSquare
General form:
GRect
which
Is restricted to equal height and width
public class DerivedClassName extends ParentClass
{
// Members go here
}
Can be created with a given color
Notes
super refers to the parent class.
Example from GSquare Class:
this refers to the current object being defined.
public class GSquare extends GRect
{
// Rest of the definition goes here
}
When no receiver is specified the message is sent to the current
object. In other words, message() is the same as
this.message()
Notice the package inclusion just before the import statements.
26
25
The GSquare Definition
The GSmartSquare Class
A GSmartSquare
is-a
GSquare which knows:
How to find its window
See Lab Writeup
Whether its left or right edge has gone out of the window
Whether its top or bottom edge has gone out of the window
Whether its fits in its window
27
28
The GSmartSquare Class Definition
A Square and Still More. . .
A GMovingSquare
is-a
GSmartSquare which:
Keeps track of a displacement (x- and y-coordinate)
Knows how to move by this displacement
See Lab Writeup
You will be completing this class in lab
We can derive this class from GSmartSquare by adding:
displacement: a new attribute to keep track of ∆x and
∆y for the object
move: a message to make a move based on this
displacement
a constructor that initializes the displacement as well as the
other usual attributes of a GSquare object
29
30
The GMovingSquare Class Definition
Noteworthy
When we need to refer to a parent class or one of its constructors
from within a derived class method, we preface the call with super.
When we need to distinguish a derived class method from a parent
class method or a parameter, we preface the call with this.
See Lab Writeup
You will be completing this class in lab
We can also use this to call a constructor from within another
constructor.
We will place the new graphics classes in their own package, called
mat2170.graphics.
Any non-primitive variable can be set equal to null which is
sometimes a useful way to initialize it.
31
32
About the Pool Table Exercise
GOval objects have the methods: getWidth(), getHeight(),
and setVisible().
However, even though ActiveCount can be initialized when it is
declared, it should also be set to the number of pool balls within
the run() method in order for it to work correctly once published
to the web and RELOAD is used to re-execute the applet.
Ball.setVisible(false) erases the object from the graphics
window.
When publishing to the web, you’ll need to include the
circleLibrary.jar in addition to the acmLibrary.jar.
You must be clear in your mind between methods in your circle
classes and those in the program — i.e., whether a method is to
be part of a class or added below run().
In order to keep count of the active balls, you need to make
ActiveCount a “global” object; declare and initialize it outside
the run() method so it is accessible to other methods in the
program. In this way, you do not need to send it as a parameter
to a method; just access it directly.
33
This lab is worth 50 points, and is not due for two weeks (rather
than the usual one) from Thursday.
34
Controlling Access to Entries
Designer versus Client View of Class Members
Each entry in a Java class is marked with a keyword to control
which classes have access to that entry.
Clients can access these
Public members
The types of access are termed public, private, and
protected.
Protected members
The text uses only public and private. All entries are marked
as private unless there is a compelling reason to export them.
&
Private members
Clients cannot access these!
35
36
Access Privileges
public
The Structure of Memory
bit: a fundamental unit of information found in one of two
possible states: off and on — or false / true — or 0 / 1.
All classes in the program have access;
public entries in a class are said to be
exported by that class.
private
Access is limited to the class itself, making that entry completely invisible outside the class.
protected
Access is restricted to the class that defines these entities, along with any of
its subclasses or any classes in the same
package.
(no keyword)
The entry is visible only to classes in the
same package, and are called package–
private.
37
byte: 8 bits
nybble: 4 bits or half a byte
word: 4 bytes
kilo (K)
mega (M)
giga (G)
=
=
=
210
220
230
=
=
=
1,024
1,048,576
1,037,741,824
A 64KB computer from the early 1970’s would have had 64 ×
1024 or 65,536 bytes of memory.
A 512MB machine would have 512 × 1,048,576 or 536,870,912
bytes of memory.
38
Binary notation — a Byte
Hexadecimal — Base 16 — 4 Bits Each
Hex digit Value
A
10
B
11
C
12
D
13
E
14
F
15
0 0 1 0 1 0 1 0
1
2
4
8
16
32
64
128
= 0
= 2
= 0
= 8
= 0
= 32
= 0
= 0
42
39
0 0 1 0 1 0 1 0
A
2
2 A
10 x 1 = 10
2 x 16 = 32
42
40
Memory and Addresses
Allocating Memory
Within the memory system of a typical computer, every byte is
identified by a numeric address, starting at 0.
Whenever a variable or object is declared, the compiler must
reserve space in memory to hold its value/s.
0000
0001
0002
0003
allocation: the process of reserving memory space.
1000
1001
1002
Memory is allocated from one of three different regions of
memory depending on how an object is declared:
FFFD
FFFE
FFFF
If we use two bytes to hold addresses, the largest address is: FFFF
or 15 × 163 + 15 × 162 + 15 × 161 + 15 × 160 or 65,535.
It takes 4 bytes, or a word, to be able to address a gig of memory.
41
42
1
The beginning of memory
2
The stack
3
The heap
Allocation Strategies — Beginning or Low Memory
Memory regions
memory for
program code
and static data
Static variables and constants.
pool of memory
available for objects
(the "heap")
static variables belong to the whole class, not to an individual
object.
the heap grows
toward higher addresses
This group is usually allocated at the beginning of the memory
space.
the stack grows
toward lower addresses
Program instructions are also stored at the beginning of memory.
memory for
local variables
(the "stack")
43
44
Allocation Strategies — The Heap
Allocation Strategies — The Stack
Local variables.
All variables that are declared as local variables inside a method
are allocated from a region of memory called the stack.
Dynamically allocated objects.
Convention places the beginning of stack memory at the highest
legal address in memory.
All objects created using new are assigned storage from a region
of memory called the heap.
The stack grows toward lower addresses as new methods are
called.
Convention places the heap memory immediately after the fixed
region assigned to the static declarations of a class.
When a method is invoked, the size of the stack increases by the
amount needed to hold the local variables that method declares.
The memory set aside for a particular method is called a stack
frame.
The heap grows toward higher addresses.
When a method returns, its stack frame is discarded, restoring
the frame of its caller.
46
45
What’s Important to Know
What’s Important to Know
The full story is that non-primitive variables are references.
A reference is just a memory address of some object. However,
we can send message to an object via a reference to it.
When we pass a reference as a parameter to a method the method
still just gets a copy of it.
When a primitive type is passed as a parameter, a copy of its
value is made. Changes, if any, are made to the copy.
However, having a copy of a reference is just like having the
original.
When an object is passed as a parameter to a method, a
reference to that object is passed. Changes, if any, are made to
the original object.
47
The null literal is a reference that refers to no object. Any
non-primitive variable can be set equal to null which is sometimes
a useful way to initialize it.
48