3 Classes and Other Concepts
3 Classes and Other Concepts
3 Classes and Other Concepts
Readings
Chapter 7: Introduction to Classes and Objects
Chapter 8: Classes and Objects: A Deeper Look
◦ If parameter names for the constructor are identical to the class’s instance-variable names
then this reference is used to refer to the instance variables.
Can access a class’s public static members through a reference to any object
of the class
private static class members can be accessed by client code only through
methods of the class.
String objects in Java are immutable—they cannot be modified after they are
created.
Therefore, it’s safe to have many references to one String object.
This is not normally the case for objects of most other classes in Java.
If String objects are immutable, you might wonder why are we able to use
operators + and += to concatenate String objects.
String-concatenation actually results in a new String object containing the
concatenated values—the original String objects are not modified.
* indicates that all static members of the specified class should be available
for use in the class(es) declared in the file.
Keyword final specifies that a variable is not modifiable (i.e., it’s a constant) and any attempt
to modify it by assignment after it’s initialized is an error.
EX:
private final int INCREMENT;
// Declares a final (constant) instance variable INCREMENT of type int.
final variables can be initialized when (1) they are declared or (2) by each of the class’s
constructors so that : each object of the class has a different value.
If a class provides multiple constructors, every one would be required to initialize each final
variable.
If a final variable is not initialized, then a compilation error occurs.
The JVM performs automatic garbage collection to reclaim the memory occupied
by objects that are no longer used.
When there are no more references to an object, the object is eligible to be
collected.
Collection typically occurs when the JVM executes its garbage collector, which
may not happen for a while, or even at all before a program terminates.
Memory leaks that are common in other languages like C and C++ (because
memory is not automatically reclaimed in those languages) are less likely in Java,
but some can still happen in subtle ways.
Every class in Java has the methods of class Object (package java.lang), one
of which is method finalize.
You should never use method finalize, because it can cause many problems.
The original intent of finalize was to allow the garbage collector to perform
termination housekeeping on an object just before reclaiming the object’s memory.