Introduction To Java Programming: Week 5
Introduction To Java Programming: Week 5
Chapter 8
Week 5
Review of Instance Fields and Methods
• Each instance of a class has its own copy of instance variables.
• Example:
• The Rectangle class defines a length and a width field.
• Each instance of the Rectangle class can have different values stored in
its length and width fields.
• Instance methods require that an instance of a class be created
in order to be used.
• Instance methods typically interact with instance fields or
calculate values based on those fields.
Static Class Members
• Static fields and static methods do not belong to a single instance of a
class.
• To invoke a static method or use a static field, the class name, rather
than the instance name, is used.
• Example:
public Countable()
{
instanceCount++;
}
objectCount = object1.getInstanceCount();
instanceCount field
(static)
Address
balance: 3200.0
address
• Now, objects can be compared by their contents rather than by their memory addresses.
• See example: StockCompare.java
Methods That Copy Objects
• There are two ways to copy an object.
• You cannot use the assignment operator to copy reference types
• Example: ObjectCopy.java
Copy Constructors
• A copy constructor accepts an existing object of the same class and clones it
account2 Address
account2 Address