CSE 501N Fall ‘06 02: Machine Overview + Fundamental Types

Download Report

Transcript CSE 501N Fall ‘06 02: Machine Overview + Fundamental Types

CSE 501N
Fall ‘09
04: Introduction to Objects
08 September 2009
Nick Leidenfrost
Lecture Outline



Lab 1
Static Methods
Objects

Fields / Instance Variables
 Object Variables

Aliases

Creating Objects: Constructors
 Accessing Fields / Invoking methods on Objects




The String Object
Object Assignment
Access Modifiers
Variable Scopes
2
Static Methods
Calling Methods Without Objects
In Java, all methods must be defined
within a class body
 At times it is useful to have a method
which defines functionality that does not
alter the state of an object

Java Library class java.lang.Math is a
perfect example of useful static methods
 The
Methods in Math give us functionality that is not
native to the Java language
 These functions are strictly input / output functions
and do not alter the state of any Math object

3
Static Methods
Calling / Invoking

Static methods are typically invoked in the
following way:
<Class Name> . <Method Name> <Method Parameters>
int myNum = 5;
int cubed = Math.pow(myNum, 3);
4
Classes
Further detail

A class is a template (or blueprint) for creating
Objects

Often representative of real-world concepts
 Defines state (fields)
 Defines behavior (methods)
public class BankAccount {
// Fields / Methods defined here.
}
5
Class Members: Fields
Thinking in OO


An class’s fields (a.k.a. instance variables)
define the internal state
Just as classes often mimic real-world concepts,
fields often represent real attributes of those
concepts
public class BankAccount {
double balance;
int accountNumber;
Person owner;
}
6
Class Members: Fields
Referencing Fields

Fields can be used in all class methods by name
There is no local variable
declared in this method
named balance.
public class BankAccount {
Therefore, Java knows we
are referring to the
double balance;
instance variable.
int accountNumber;
public double getBalance () {
return balance;
}
}
7
Objects

Objects are instances of classes
 (Real

examples of the concept defined by a class)
Each object gets its own copy of all
instance variables
 This
internal state is specific to each object
Nick’s BankAccount
balance
accountNum
-573.17
George’s BankAccount
Sally’s BankAccount
1858323356
balance
accountNum
balance
14,068.00
accountNum 3988323425
1,584,001.01
225323693
8
Object Variables
Declaring Variables with Object Types

We can declare variables to hold Object values just like we
can with primitives

A class name is used as the type when declaring an object
variable
String title;

Note that no object is created with this declaration


Object variables hold the special value null if they are not
initialized
The object itself must be created separately

With its constructor
9
Aliases

Two or more references (variables) 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 will naturally occur in programming, 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
10
Creating Objects
Constructors

Constructors are special methods that create the objects of a class

Allocate Memory required to store object state (instance variables);

Initialize object state per programmer instructions

Constructors give the programmer a chance to initialize the state (instance
variables) of an object

Constructors must have the same name as the class in which they are
defined

Constructors have no return type specified in the method header, not even
void
public class BankAccount {
public BankAccount () {
// Initialization code here
}
}
11
Creating Objects
Constructors

Can accept parameters like methods
public BankAccount (int accountNum, double amount) {
…
Can also be
}
overloaded like
methods
protected BankAccount () {
}

Each class has a default constructor that accepts no
parameters
 The
programmer does not have to define a
constructor for a class - Java will define a default
constructor for us if we do nothing
12
Creating Objects
The new Operator

Generally, we use the new operator to invoke an
object’s constructor
BankAccount account = new BankAccount(156774, 0.0);
The new operator is used to
invoke the constructor

The constructor cannot be called without new

Creating an object is called instantiation
13
Creating Objects
Overloaded Constructors

If a constructor is overloaded we can call
one version from another with the this
keyword
public BankAccount (int accountNumber, double initBalance) {
accountNum = accountNumber;
balance = initBalance;
}
public BankAccount (int accountNumber) {
this(accountNumber, 0.0);
}

this also has other uses that we will
learn about soon.
14
Creating Objects
Return Statements
Constructors by definition return an object
whose type is that of the constructors’
class
 You may have a return statement inside
of a constructor

 Only
for returning from the constructor call
early
 You may not return a value
15
Invoking Methods on Objects

Once an object has been instantiated, we can
use the dot operator to invoke its methods
 Dot
operator syntax:
<Object Variable Name> . <Method Name> <Method Parameters>
BankAccount acct = new BankAccount();
double balance = acct.getBalance();

A method invocation can be thought of as
asking an object to perform a service or to
manipulate its state
16
Method Control Flow

The called method may be part of another class
or object
ATM
void main ()
acct.getBalance();
BankAccount
double getBalance() void helper ()
helper();
17
Referencing Fields of Objects

Once an object has been instantiated, we can also use
the dot operator to access its fields
BankAccount account = new BankAccount();
// … omitted statements
double canSpend = account.balance;
account.balance = 15000;

Referencing fields in this way is generally discouraged
with a few exceptions

Instance variables should typically be accessed and
modified using accessor and mutator methods
18
The String Object
A Primitive? An Object? Superman?



Earlier, we learned about the char data type,
used to store a single character
In Java, the String object represents
Also referred toa series (or
string) of characters
as string literals
String constants in Java are encapsulated by
double quotes
 String

name = “Peter”;
Strings are Objects in Java
 Lots
 int
of predefined functionality
length = name.length();
19
The String Class

Java implicitly
calls the
Because strings are so common,
we don't
have
String constructor when a
to use the new operator to create
a String
String literal
is assigned to
String literal
variables
object with a string constant / string
String text = “was it a rat I saw";

This is special syntax that works only for strings

Each string literal (enclosed in double quotes)
represents a String object
20
The String Object

Strings can be “added” like numeric
primitives with the ‘+’ and ‘+=‘ operators
 This
is referred to as concatenation
String firstName = “George”;
String lastName = “Henrichs”;
String name = firstName + “ “ + lastName;
// “George Henrichs”
// ...Or
String name = lastName;
name += “, “ + firstName;
// “Henrichs, George”
21
The String Object

Strings can be also concatenated with primitive
types:
String name = “George”;
double examGrade = 89.7;
String output = name + “ received an “ + examGrade + “% on
exam 1”;
// “George received an 89.7% on exam 1”

The resultant type of an expression is the widest
type of the operands of that expression
 Strings
are “wider” than any type
22
Of Strings and Objects
The toString Method

We can define a special method toString to specify
the String representation of an object
public String toString () {
return accountNum + “: “ + balance;
}


A default implementation of toString is provided for us if we
don’t define one
This allows object variables to be concatenated with
Strings:
BankAccount account = new BankAccount(10000, 50000.0);
System.out.println(“The account: “ + account);
23
Printing Strings to the Command Line
System.out.print and System.out.println

We can print any String to the command line
with two methods provided by Java
 System.out.print
 System.out.println
String name = “George”;
double examGrade = 89.7;
String output = name + “ received an “ + examGrade + “% on
exam 1”;
System.out.println(output);
24
String Methods
Immutable Objects

Once a String object has been created, neither its
value nor its length can be changed

Thus we say that an object of the String class is
immutable

However, several methods of the String class return
new String objects that are modified versions of the
original
25
Variable Declaration
Primitive Variables vs. Object Variables
If the variable is a primitive, the
When a variable is declared,
whether
it’s a
appropriate
amount is allocated
basedallocates
on the variable’s
type
primitive or an object, Java
memory
to
e.g.
store the variable
8 bytes
for athe
double
Any value
primitive
Really, a variable is just a
human-readable
“nickname” for a memory
address
4 bytes
int myCount;
String name;
Your
Computer’s
Memory
4 bytes
for
anobject,
inthave4will
If thevariable
variable
is an
will
ever
(RAM)
1are
byte
forina this
char
bytes
allocated
for
the
be
stored
memory.
object handle.…etc.
This memory will
0
later point to the object
referenced by ‘name’.
4 bytes

null
26
Variables and Assignment
Primitive Variables vs. Object Variables
Assignment Affects Object and Primitive
Variables Differently
int myCount;
String name;
Your Computer’s Memory
When the constructor is
(RAM)
invoked (called) Java
allocates
memory
fornow
the refers to
The object
handle
object.
2
0
the
store newly created object.
myCount = 2;
name = new String(“Bob”);
4 bytes 4 bytes

(Memory Address)
null
“Bob”
27
Object Variable Reassignment
Implicitly calls the
name; String constructor
String
name = new String(“Bob”);
name = “Robert”;
Your Computer’s Memory
(RAM)
(Memory Address)
“Bob”
“Robert”
28
Object Aliases
Two References to the Same Object
(Multiple References to
the Same Object)

String name = “Bob”;
String aName;
aName = name;
name = null;
String anotherName = “Bob”;
Your Computer’s Memory
(RAM)
null
(Memory Address)
“Bob”
(Memory Address)
null
(Memory Address)
null
“Bob”
29
Primitive Assignment

Value is copied
int myCount = 2;
int numGuests;
numGuests = myCount;
Your Computer’s Memory
(RAM)
2
0
2
30
Object Interaction
Access Modifiers

Access modifiers allow us to control who has access to an
object’s members




Who can reference Fields (internal state)
Who can invoke Methods (behavior)
Who can invoke Constructors
Java provides four types of access modifiers

public


protected


Only other instances of this class and their subclasses
[default] or Package Protected


Anyone can read and write this field or invoke this method
(No access modifier specified) Only other classes in the package
private

Only this object and other instances of this class
31
Object Interaction
Access Modifiers

protected
and private
Using Modifiers
Protect
State
… into
instance
variable
default constructors can be
declarations
public class BankAccount
{
created
to prevent Java from
defining a public default
private double balance;
constructor
protected BankAccount () {
}
public boolean deposit (double amount) {
if (amount <= 0)
return false;
balance
+= amount;
… in method
Note that local
return
true;
declarations
variables (variables
}
declared within
methods) (double
cannot have
public boolean withdraw
amount) {
if (amount access
<= 0) modifiers.
return false;
double newBalance = balance – amount;
32
Object Interaction
Encapsulation


We may not want to give others unlimited
access to an object’s state
Force the outside world to interact with a class
and its state through predefined methods
Generally, it is a bad
idea to allow
direct
Accessor
methods
allow
access
class’s
accesstotoarequired
new BankAccount();
fields. without
information
exposing objects fields
BankAccount account =
// ...
double balance = account.balance;
double balance = account.getBalance();
33
Object Interaction
Encapsulation

If an access modifier is
used when a class
member is declared, any
access prohibited by that
access modifier becomes
a compilation error
public class BankAccount {
private double balance;
// Omitted methods, etc
}
// Outside of
BankAccount.java
X The
field BankAccount.balance is not visible.
BankAccount account = new BankAccount();
// ...
double balance = account.balance;
34
Scopes
The Lifespan and Visibility of a Variable
 A scope of a variable defines
the context in which it is
accessible

Usually surrounded by brackets: { }

State or instance variables are accessible from
any method in the class
declared public / default / protected,
accessible from other classes as well
 If

Local variables are accessible only within the
method in which they are declared
 Local
variables “die” after the method returns
35
Local
Variables
 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
 Primitive
 Object

parameters are copied
parameters are aliased
What happens in the method doesn’t necessarily stay in the
method

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
36
Garbage Collection

Automatic Memory Management

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
37
Conclusion

Questions?

Lab 1 due Thursday

I will be in lab now.
38