Chapter 6 - Objects and Classes
Chapter 6 - Objects and Classes
Chapter 6 - Objects and Classes
[email protected]
Mantra:
Coding is fun!
Chapter 6 Objects and Classes
• OO Programming Concepts
• Creating Objects and Object Reference Variables
• Differences between primitive data type and object type
• Automatic garbage collection
• Constructors
• Modifiers (public, private and static)
• Instance and Class Variables and Methods
• Scope of Variables
• Use the this Keyword
• Case Studies (Mortgage class and Count class)
OO Programming Concepts
Data Field
data field 1
radius = 5
... State
Method
data field n findArea
method 1
... Behavior
method n
Class and Objects
double findArea(){
return radius * radius * 3.14159;
}
}
Declaring Object Reference Variables
ClassName objectReference;
Example:
Circle myCircle;
Creating Objects
objectReference = new ClassName();
Example:
Example:
Circle myCircle = new Circle();
Differences between variables of
primitive Data types and object types
c: Circle
Created using
new Circle() radius = 1
Copying Variables of Primitive Data Types
and Object Types
i 1 i 2 c1 c1
j 2 j 2 c2 c2
radius = 5 radius = 9
Garbage Collection
As shown in the previous
figure, after the assignment
statement c1 = c2, c1 points
to the same object
referenced by c2. The object
previously referenced by c1
is no longer useful. This
object is known as garbage.
Garbage is automatically
collected by JVM.
Garbage Collection, cont
TIP: If you know that an
object is no longer needed,
you can explicitly assign
null to a reference
variable for the object.
The Java VM will
automatically collect the
space if the object is not
referenced by any variable.
Accessing Objects
• Referencing the object’s data:
objectReference.data
myCircle.radius
objectReference.method
myCircle.findArea()
Example 6.1 Using Objects
myCircle: Circle
radius = 1
Instance
Variables, and Methods
circle1:Circle 1 radius
instantiate -radius = 1
radius is an instance CircleWithStaticVariable -numOfObjects = 2
variable, and
numOfObjects is a -radius
class variable -numOfObjects
2 numOfObjects
+getRadius(): double instantiate
+setRadius(radius: double): void circle2:Circle
+getNumOfObjects(): int
+findArea(): double
-radius = 5 5 radius
-numOfObjects = 2
Example 6.6
Using Instance and Class Variables and Method
… Circle object 1
• java.awt
Contains classes for graphics.
• java.applet
Contains classes for supporting applets.
Java API and Core Java classes,
cont.
• java.io
Contains classes for input and output
streams and files.
• java.util
Contains many utilities, such as date.
• java.net
Contains classes for supporting
network communications.
Java API and Core Java classes,
cont.
• java.awt.image
Contains classes for managing bitmap images.
• java.awt.peer
Platform-specific GUI implementation.
• Others:
java.sql
java.rmi