Download Chapter #, Title - Montclair State University

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 4
Writing Classes
Java Software Solutions
Foundations of Program Design
Seventh Edition
John Lewis
William Loftus
Copyright © 2012 Pearson Education, Inc.
Agenda
• Variables
• Primitive vs. Object Types
• Keyword static
Copyright © 2012 Pearson Education, Inc.
Variables
• Fields are one sort of variable
– They store values through the life of an object
– They are accessible throughout the class
• Methods can include shorter-lived variables
(parameters and local variables)
– They exist only as long as the method is being executed
– They are only accessible from within the method
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Fields / Instance Data
• A variable declared at the class level (such as x) is
called instance data or a field
• A field declares the type of the data, if it is an object
type (a class) it does not create the object
– We need to use new to call a constructor and assign it to
that variable
• Objects of a class share the same method definitions,
but each object has its own data space
• That's how two objects can have different states
x
10
x
25
y
25
y
45
Parameters
• Often, we do not know the values the user will need
to use in the constructor, or in any method
• So we use a variable in the parameter list; the name
of the variable is called a formal parameter
• The value the user/programmer passes to the
method, the value that will be stored in the formal
parameter, i.e. 500, is the actual parameter
Parameters
• When a method is called, the actual parameters in
the invocation are copied into the formal parameters
in the method header
ch = obj.calc(25, count, "Hello");
public char calc(int num1, int num2, String message)
{
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
}
Copyright © 2012 Pearson Education, Inc.
Parameters
• Formal parameters are only available to use in the
method that declares it
• For example, int num1 and num2 can only be used
in the calc method, not in any other method
• In technical language, we say the scope of the
parameter is restricted to the body of the
constructor or method in which it is declared
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Local Data
• As we’ve seen, local variables can be declared
inside a method
• The formal parameters of a method create
automatic local variables when the method is
invoked
• When the method finishes, all local variables are
destroyed (including the formal parameters)
• Keep in mind that instance variables, declared at
the class level, exists as long as the object exists
Copyright © 2012 Pearson Education, Inc.
To “keep” data, store it in fields
Local data that will disappear
So we need to store it
in the fields
Local variables
A local variable
No visibility
modifier
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
Remember: No type
when using variables
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Local variables
Local variables
Scope of Variables
• Scope – the set of curly braces in which the
variable can be used
• Examples:
– Formal parameters & local variables
• The scope is the method
– Fields
• The scope is the entire class definition
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Scope Example
public class TicketMachine {
public TicketMachine(int ticketCost)
{
price = ticketCost;
balance = 0;
total = 0;
}
{
// Rest of class omitted
}
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Scope Example: Undergraduate
• Identify scope of:
– Fields
– Parameters
– Local variables
Scope and life time
• The scope of a local variable is the block it is
declared in
• The lifetime of a local variable is the time of
execution of the block it is declared in
• Lifetime is dynamic & determined precisely at
runtime, whereas scope is static
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Variable Lifetime
• Lifetime of a variable = when does the variable exist?
• What happens if you call the a method (with a parameter)
more than once?
– The lifetime of a parameter is limited to a single call of the method.
– If you call the method more than once, the parameter is created,
then removed once the method is done.
– Thus, if you have 5 methods calls, the parameter is created 5 times.
• What is the lifetime of a field?
– Is the same as the lifetime of the object
– The field is created when the object is created and destroyed when
the object is removed
Variable Recap
• Types of variables
– Fields
– Parameters
– Local variables
• Scope & lifetime
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Primitive vs. Object Types
• What are the difference between object and
primitive types?
– 8 primitive data types (all start with lower case)
– A library of classes, and we can make our own
(all start with upper case)
• Are there more differences though?
Object Types & References
primitive type
int num1
45
38
"Bill Gates"
object type
String name1
"Steve Jobs"
null
• A primitive variable contains the value itself, but an
object variable contains the address of the object
• An object reference can be thought of as a pointer
to the location of the object
• Rather than dealing with arbitrary addresses, we
often depict a reference graphically
Copyright © 2012 Pearson Education, Inc.
Assignment (Primitive types)
• The act of assignment takes a copy of a value and
stores it in a variable
• For primitive types (e.g. int):
Before:
num1
38
num2
96
num1
38
num2
38
num2 = num1;
After:
Copyright © 2012 Pearson Education, Inc.
Assignment: Object/reference Types
• For object references, assignment copies the
address (e.g. String):
Before:
name1
"Steve Jobs"
name2
"Steve Wozniak"
name1
"Steve Jobs"
name2 = name1;
After:
name2
Copyright © 2012 Pearson Education, Inc.
Aliases
• Two or more references that refer to the same
object are called aliases of each other
• That creates an interesting situation: one object
can be accessed using multiple reference variables
• Aliases can be useful, but should be managed
carefully
• Changing an object through one reference
changes it for all of its aliases, because there is
really only one object
Copyright © 2012 Pearson Education, Inc.
Quiz: What is the output?
• int a;
int b;
a = 32;
b = a;
a = a + 1;
System.out.println(b);
• Person a;
Person b;
a = new Person("Everett");
b = a;
a.changeName("Delmar");
System.out.println( b.getName());
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Primitive vs. Object Types
ObjectType a;
ObjectType b;
b = a;
int a;
32
int b;
32
Objects First with Java - A Practical Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Ellipse/Rectangle Examples
sun
x
10
y
25
width
60
height
75
blue {0,0,255}
fillColor
grass
x
100
y
200
width
250
height
75
fillColor
red {255,0,0}
Garbage Collection
• When an object no longer has any valid references
to it, it can no longer be accessed by the program
• The object is useless, and therefore is called
garbage
• Java performs automatic garbage collection
periodically, returning an object's memory to the
system for future use
• In other languages, the programmer is responsible
for performing garbage collection
Copyright © 2012 Pearson Education, Inc.
Static Class Members
• Recall that a static method is one that can be
invoked through its class name
• For example, the methods of the Math class are
static (also called class methods):
result = Math.sqrt(25)
• Variables can be static as well
Copyright © 2012 Pearson Education, Inc.
The static Modifier
• We declare static methods and variables using the
static modifier
• It associates the method or variable with the class
rather than with an object of that class
– Static methods are sometimes called class methods
– Static variables are sometimes called class variables
Copyright © 2012 Pearson Education, Inc.
Static Variables
• Normally, each object has its own data space, but if a
variable is declared as static, only one copy of the
variable exists
private static float price;
• Memory space for a static variable is created when the
class is first referenced
• Using the final modifier you can also create static
constant values (e.g. Math.PI and Color.RED)
• All objects instantiated from the class share its static
variables
• Changing the value of a static variable in one object
changes it for all others
Copyright © 2012 Pearson Education, Inc.
Static Variable Example (Ellipse)
sun
static x
10
static y
25
width
60
height
60
blue {0,0,255}
fillColor
moon
x
y
width
100
height
100
fillColor
red {255,0,0}
Static Methods
public class Helper
{
public static int cube (int num)
{
return num * num * num;
}
}
• Because it is declared as static, the cube method
can be invoked through the class name:
value = Helper.cube(4);
Copyright © 2012 Pearson Education, Inc.
Static Class Members
• Recall that the main method is static – it is invoked by
the Java interpreter without creating an object
• Static methods cannot reference instance variables
(fields) because instance variables don't exist until an
object exists
• However, a static method can reference static variables
or local variables
• Static methods and static variables often work together
• The following example keeps track of how many
Slogan objects have been created using a static
variable, and makes that information available using a
static method
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Slogan.java
Author: Lewis/Loftus
//
// Represents a single slogan string.
//********************************************************************
public class Slogan
{
private String phrase;
private static int count = 0;
//----------------------------------------------------------------// Constructor: Sets up the slogan and counts the number of
// instances created.
//----------------------------------------------------------------public Slogan (String str)
{
phrase = str;
count++;
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Returns this slogan as a string.
//----------------------------------------------------------------public String toString()
{
return phrase;
}
//----------------------------------------------------------------// Returns the number of instances of this class that have been
// created.
//----------------------------------------------------------------public static int getCount ()
{
return count;
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// SloganCounter.java
Author: Lewis/Loftus
//
// Demonstrates the use of the static modifier.
//********************************************************************
public class SloganCounter
{
//----------------------------------------------------------------// Creates several Slogan objects and prints the number of
// objects that were created.
//----------------------------------------------------------------public static void main (String[] args)
{
Slogan obj;
obj = new Slogan ("Remember the Alamo.");
System.out.println (obj);
obj = new Slogan ("Don't Worry. Be Happy.");
System.out.println (obj);
continue
Copyright © 2012 Pearson Education, Inc.
continue
obj = new Slogan ("Live Free or Die.");
System.out.println (obj);
obj = new Slogan ("Talk is Cheap.");
System.out.println (obj);
obj = new Slogan ("Write Once, Run Anywhere.");
System.out.println (obj);
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
Copyright © 2012 Pearson Education, Inc.
continue
Output
Remember
the or
Alamo.
obj = new Slogan
("Live Free
Die.");
Don't
Worry. Be Happy.
System.out.println
(obj);
Live Free or Die.
obj = new Slogan
("Talk
is Cheap.");
Talk
is Cheap.
System.out.println
(obj);
Write
Once, Run Anywhere.
obj = new Slogan ("Write Once, Run Anywhere.");
Slogans
created: 5
System.out.println
(obj);
System.out.println();
System.out.println ("Slogans created: " + Slogan.getCount());
}
}
Copyright © 2012 Pearson Education, Inc.
Quick Check
Why can't a static method reference an instance
variable (field)?
Because instance data is created only when an
object is created.
You don't need an object to execute a static method.
And even if you had an object, which object's instance
data would be referenced? (remember, the method is
invoked through the class name)
Copyright © 2012 Pearson Education, Inc.
Recap
• Variables
– Types: fields, parameters, local
– Scope & lifetime
• Primitive vs. Object Types
• Keyword static
Copyright © 2012 Pearson Education, Inc.
Homework
• CodingBat
• Start studying for exam
• Understand concepts from Chapters 1-4
Copyright © 2012 Pearson Education, Inc.
Related documents