0% found this document useful (0 votes)
7 views54 pages

Java Module2

The document introduces the fundamentals of classes in Java, explaining their role as templates for objects and the distinction between classes and objects. It covers key concepts such as instance variables, methods, constructors, and memory management, including garbage collection. Examples are provided to illustrate object creation, method usage, and the importance of encapsulation in object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views54 pages

Java Module2

The document introduces the fundamentals of classes in Java, explaining their role as templates for objects and the distinction between classes and objects. It covers key concepts such as instance variables, methods, constructors, and memory management, including garbage collection. Examples are provided to illustrate object creation, method usage, and the importance of encapsulation in object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introducing Classes in Java

Class Fundamentals, Objects, Methods, Constructors, this Keyword,


and Garbage Collection

MVJCE

October 23, 2025

1 / 81
Table of Contents

1 Class Fundamentals
2 Declaring Objects
3 Assigning Object Reference Variables
4 Introducing Methods
5 Constructors
6 The this Keyword
7 Garbage Collection

2 / 81
Understanding Classes: The Foundation of Java

Core Concept
The class is at the core of Java. It is the logical construct upon which the
entire Java language is built because it defines the shape and nature of an
object.

Key Points about Classes:


Classes form the basis for object-oriented programming in Java
Any concept you wish to implement in a Java program must be
encapsulated within a class
A class defines a new data type
A class is a template for an object
An object is an instance of a class
Important Distinction:
Class: Logical construct (template)
Object: Physical reality (instance with memory)
3 / 81
General Form of a Class
Basic Structure:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
} 4 / 81

Components:
Instance Variables: Data defined within a class
Methods: Code contained within the class
Members: Collective term for methods and variables
Understanding Instance Variables
What are Instance Variables?
Variables defined within a class
Called ”instance” variables because each instance (object) of the class
contains its own copy
Data for one object is separate and unique from data for another
Acted upon and accessed by methods defined for that class

Key Principle:
Methods determine how a class’s data can be used
Instance variables are accessed through methods (encapsulation)
Each object maintains its own set of instance variables

Important Notes:
Most methods will not be specified as static or public
Classes don’t need a main() method unless they’re the starting point
Some Java applications don’t require main() at all
5 / 81
A Simple Class Example
The Box Class:
class Box {
double width;
double height;
double depth;
}
What This Defines:
A new data type called ”Box”
Three instance variables: width, height, depth
Currently contains no methods
Creates a template - no actual objects exist yet

Critical Understanding:
Class declaration only creates a template
Does not create actual objects
Objects must be explicitly created using specific statements
6 / 81
Object Creation: A Two-Step Process

Step 1: Declaration
Declare a variable of the class type
This variable does not define an object
It’s simply a variable that can refer to an object
Step 2: Instantiation
Acquire an actual, physical copy of the object
Assign it to the variable using the new operator
The new operator dynamically allocates memory at runtime

Why Two Steps?


Provides flexibility in object management
Allows for efficient memory usage
Enables reference-based object handling

7 / 81
Object Declaration Syntax

Combined Approach (Most Common):

Box mybox = new Box(); // create a Box object called mybox

Two-Step Approach:

Box mybox; // Step 1: declare reference to object


mybox = new Box(); // Step 2: allocate a Box object

What Happens:
First line declares mybox as a reference to a Box object
At this point, mybox does not refer to an actual object
Second line allocates an object and assigns reference to mybox
After second line executes, you can use mybox as a Box object
In reality, mybox holds the memory address of the actual Box object

8 / 81
Understanding the ’new’ Operator
General Form:
class-var = new classname();
Components:
class-var: Variable of the class type being created
classname: Name of the class being instantiated
Parentheses: Specify the constructor for the class

Constructor Behavior:
Constructor defines what occurs when object is created
If no explicit constructor is specified, Java provides default constructor
Default constructor is what Box uses initially

Memory Management:
new allocates memory during runtime
Program can create as many or as few objects as needed
If insufficient memory exists, runtime exception occurs
9 / 81
Primitive Types vs. Object Types
Why Don’t Primitives Need ’new’ ?
Java’s primitive types are not implemented as objects
They are implemented as ”normal” variables for efficiency
Objects have many features and attributes requiring special treatment
By not applying object overhead to primitives, Java implements them
more efficiently

Object Benefits:
Flexibility in memory allocation
Dynamic creation during program execution
Automatic memory management through garbage collection

Class vs. Object Distinction:


Class: Creates logical framework defining member relationships
Object: Has physical reality and occupies memory space
10 / 81
Accessing Object Members
The Dot Operator (.):
Links object name with instance variable name
Used to access both instance variables and methods
Formally categorized as a ”separator” in Java specification
Commonly referred to as ”dot operator”
Syntax:
[Link] = value;
[Link]();
Example:
[Link] = 100; // assign value to width variable of mybox
What This Does:
Tells compiler to assign value to the copy of width contained within
mybox object
Each object has its own copy of all instance variables
11 / 81
Complete Box Program Example

// Demonstration of Box class ([Link])


class Box {
double width, height, depth;
}

class BoxDemo {
public static void main(String[] args) {
Box mybox = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;

double vol = [Link] * [Link] * [Link];


[Link]("Volume is " + vol);
}
}

12 / 81
Important Compilation and Execution Notes
File Naming:
File should be called [Link] (contains main() method)
Java compiler automatically puts each class in its own .class file
Will create both [Link] and [Link]
Class File Organization:
Not necessary for both classes to be in same source file
Could separate into [Link] and [Link]
Execute [Link] to run the program
Program Output:
Volume is 3000.0
Object Independence:
Each object has its own copies of instance variables
Changes to one object’s variables don’t affect another object
This is fundamental to object-oriented programming
13 / 81
Multiple Objects Example
// Demonstration with two Box objects
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();

[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;

double vol1 = [Link] * [Link] * [Link];


double vol2 = [Link] * [Link] * [Link];

[Link]("Volume of Box1: " + vol1);


[Link]("Volume of Box2: " + vol2);
}
} 14 / 81
Output and Key Insights
Program Output:

Volume is 3000.0
Volume is 162.0

Key Insights:
mybox1 and mybox2 are completely separate objects
Each maintains its own set of instance variables
[Link] is completely different from [Link]
Modifying one object has no effect on the other

Memory Visualization:
Two separate memory locations allocated
Each contains width, height, and depth variables
Variables in each object can hold different values
This separation is automatically maintained by Java
15 / 81
Object Reference Assignment: A Common Misconception
Consider This Code:
Box b1 = new Box();
Box b2 = b1;
What You Might Think:
b2 is assigned a reference to a copy of the object referred to by b1
b1 and b2 refer to separate and distinct objects

This Would Be Wrong!


After this fragment executes, b1 and b2 will both refer to the same
object.

What Actually Happens:


Assignment of b1 to b2 does not allocate memory
Does not copy any part of the original object
Simply makes b2 refer to the same object as b1
16 / 81
Understanding Reference Assignment
Visual Representation:
Box object
b1 → Width
b2 → Height
Depth
Key Implications:
Any changes made to object through b2 affect the object b1 refers to
They are the same object, not separate objects
Both references point to the same memory location

Reference Independence:
Although b1 and b2 refer to same object, they are not linked
otherwise
Subsequent assignment to b1 unhooks it from original object
This doesn’t affect the object or b2
17 / 81
Reference Reassignment Example

Box b1 = new Box();


Box b2 = b1; // b1 and b2 refer to the same object
b1 = null; // b1 set to null; b2 still refers to the object

After b1 = null:
b1 becomes null
b2 still points to the same Box
Object is still accessible via b2
b1 no longer references anything

Key Point
Assigning one object reference to another copies the reference, not the object.

Memory Note:
Object stays in memory while a reference exists
Becomes eligible for garbage collection when no references remain

18 / 81
Introduction to Methods

What are Methods?


Classes usually consist of two things: instance variables and methods
Methods provide much power and flexibility in Java
The topic of methods is extensive - much of advanced Java is devoted
to methods
Methods are fundamental building blocks you need to learn now

Why Methods Matter:


Most classes use methods to access instance variables
Methods define the interface to most classes
Allow class implementors to hide internal data structure details
Provide cleaner method abstractions
Can define methods for internal class use

19 / 81
General Form of a Method
Basic Method Syntax:

type name(parameter-list) {
// body of method
}

Components Explained:
type: Specifies the type of data returned by the method
Can be any valid type, including class types you create
Must be void if method doesn’t return a value
name: The method identifier
Can be any legal identifier
Must not conflict with other items in current scope
parameter-list: Sequence of type and identifier pairs separated by
commas
Parameters receive values of arguments passed to method
Empty if method has no parameters
20 / 81
Return Statement
Returning Values:
Methods with return type other than void must return a value
Use the return statement to return values
Return Statement Syntax:
return value;
Key Points:
value is the actual value being returned
Return type must match method declaration
void methods don’t need return statement
return statement transfers control back to caller

Coming Up:
How to create methods that take parameters
How to create methods that return values
Practical examples of both types
21 / 81
Why Add Methods to Classes?
Class Design Principles:
Classes containing only data are rare
Methods provide controlled access to instance variables
Methods define the interface to most classes
Hide specific layout of internal data structures
Provide cleaner method abstractions

Box Class Volume Computation Example:


Previously: BoxDemo class computed volume externally
Better design: Box class should compute its own volume
Volume depends on box size - logical to have Box compute it
Demonstrates proper object-oriented design

Method Types:
Methods that provide access to data
Methods used internally by the class itself
Both types essential for well-designed classes
22 / 81
Adding volume() Method to Box Class
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
[Link]("Volume is ");
[Link](width * height * depth);
}}
class BoxDemo3 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
// display volume
[Link]();
[Link]();
}}
23 / 81
Program Output and Analysis
Program Output:
Volume is 3000.0
Volume is 162.0
Key Code Analysis:
[Link](); - invokes volume() method on mybox1
[Link](); - invokes volume() method on mybox2
Same output as previous version but better design

Method Call Syntax:


Object name followed by dot operator
Method name with parentheses
Each call displays volume for specified box
Method invoked relative to specific object

Important Note:
This generates the same output as the previous version
But represents much better object-oriented design.
24 / 81
Understanding Method Calls
Method Call Mechanism:
When [Link]() is executed:
1 Java runtime system transfers control to volume() code
2 Statements inside volume() execute
3 Control returns to calling routine
4 Execution resumes with line following the call

Methods as Subroutines:
In the most general sense, methods are Java’s way of implementing
subroutines
Provide modular code organization
Enable code reuse and structured programming

Concept Clarification:
If unfamiliar with method calling concepts, take time to experiment
Method invocation, parameters, and return values are fundamental
These concepts are essential to Java programming
25 / 81
Instance Variable Access in Methods
Key Observation in volume() Method:
Instance variables width, height, and depth are referenced directly
No object name or dot operator needed inside the method
This is a very important concept to understand

Why Direct Access Works:


Method is always invoked relative to some object of its class
Once invocation occurs, the object is known
Within method, no need to specify the object a second time
Variables implicitly refer to copies in the invoking object

Access Rules Summary:


From outside class: Must use object and dot operator
From within same class: Can refer to instance variables directly
Same rules apply to methods calling other methods
This supports encapsulation and clean code design
26 / 81
Limitations of Current volume() Method
Current Implementation Issues:
volume() moves computation inside Box class (good)
But it’s not the best way to implement it
What if another part of program wants volume value but not display?
Current method can only display, not provide the value for other uses

Better Approach:
Have volume() compute the volume
Return the result to the caller
Caller can then decide what to do with the value
Much more flexible and reusable design

Benefits of Returning Values:


Method can be used in calculations
Value can be stored in variables
Can be used in expressions and other method calls
Follows principle of single responsibility
27 / 81
Improved volume() Method - Returning Values
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}}
class BoxDemo4 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
// get volume
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}} 28 / 81
Understanding Return Value Assignment
Method Call in Assignment:
vol = [Link](); - method called on right side of
assignment
vol variable receives the value returned by volume()
After execution: [Link]() returns 3000, stored in vol

Two Important Rules for Return Values:


1 Return Type Compatibility: Type of data returned must be

compatible with method’s declared return type


Example: If return type is boolean, cannot return integer
2 Receiving Variable Compatibility: Variable receiving returned value
must be compatible with method’s return type
Example: vol must be compatible with double

Efficiency Note:
Actually no need for the vol variable
Can use method call directly in println() statement
29 / 81
Direct Method Use in Expressions
More Efficient Approach:
[Link]("Volume is " + [Link]());
What Happens:
When println() is executed
[Link]() is called automatically
Its return value is passed directly to println()
No intermediate variable needed

Benefits of This Approach:


More concise code
Eliminates unnecessary variables
Direct use of return values in expressions
Common pattern in Java programming

Key Understanding:
Methods that return values can be used anywhere their return type is
expected.
30 / 81
Need for Parameters in Methods
Method Generalization:
While some methods don’t need parameters, most do
Parameters allow a method to be generalized
Parameterized method can operate on variety of data
Can be used in number of slightly different situations

Simple Example - Limited Method:


Method that returns square of number 10: int square() { return
10 * 10; }
While it returns 10 squared, its use is very limited
Only works for the number 10

Improved Version with Parameter:


int square(int i) { return i * i; }
Now square() returns square of whatever value it’s called with
General-purpose method for any integer value
Much more useful and flexible
31 / 81
Parameter Usage Examples
Using the Parameterized square() Method:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
What Happens in Each Call:
First call: value 5 passed into parameter i
Second call: i receives value 9
Third call: passes value of y (which is 2)
Each call returns square of whatever data is passed

Key Benefits:
Single method works with different input values
No need to write separate methods for each possible value
Method behavior adapts based on input parameters
Demonstrates power of parameterized methods 32 / 81
Parameters vs Arguments - Important Distinction
Parameter:
Variable defined by a method that receives a value when method is
called
Example: In square(int i), i is a parameter
Part of method definition/declaration
Acts as placeholder for incoming values

Argument:
Value that is passed to a method when it is invoked
Example: In square(100), 100 is an argument
Actual data provided at method call time
Gets copied into corresponding parameter

Relationship:
When method called, argument values copied to parameters
Inside square(), parameter i receives the argument value
This copying mechanism is fundamental to method operation
33 / 81
Improving Box Class with Parameters
Current Problem with Box Initialization:
Dimensions must be set separately with sequence of statements:
[Link] = 10;
[Link] = 20;
[Link] = 15;

Why This Approach is Problematic:


1 Clumsy and Error Prone:

Easy to forget to set a dimension


Multiple separate assignments required
2 Poor Encapsulation:
In well-designed Java programs, instance variables should be accessed
only through methods
Can change method behavior, but can’t change behavior of exposed
instance variable

Better Solution:
Create method that takes dimensions as parameters
Sets each instance variable appropriately
34 / 81
Provides controlled access to object data
Box Class with setDim() Method
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
[Link](10, 20, 15);
[Link](3, 6, 9);
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}} 35 / 81
Understanding setDim() Method Operation
Method Call Analysis:
When [Link](10, 20, 15); is executed:
10 is copied into parameter w
20 is copied into parameter h
15 is copied into parameter d

Inside setDim() Method:


Values of w, h, and d are assigned to width, height, and depth
Parameters act as local variables within the method
Assignment transfers parameter values to instance variables
Object’s state is properly initialized

Benefits of This Approach:


Single method call initializes entire object
Reduces chance of errors (forgetting dimensions)
Provides controlled interface to object data
Better encapsulation and object-oriented design
Can add validation or other logic if needed
36 / 81
The Need for Constructors
The Problem:
Tedious to initialize all variables in a class each time instance is
created
Even with convenience methods like setDim(), initialization is
cumbersome
Would be simpler to have setup done when object is first created
Requirement for initialization is extremely common
The Solution: Constructors
Java allows objects to initialize themselves when created
Automatic initialization performed through constructors
Constructor initializes object immediately upon creation
Called automatically before new operator completes
Constructor Characteristics:
Has same name as the class in which it resides
Syntactically similar to a method
No return type, not even void
Implicit return type is the class type itself
37 / 81
Constructor Purpose and Behavior

Constructor’s Job:
Initialize object’s internal state
Ensure object is fully usable immediately after creation
Set object data to known, valid state
Perform necessary setup operations

When Constructor is Called:


Automatically called during object creation
Executes before new completes
Cannot be invoked directly
Each object triggers constructor execution

Default Constructor:
Java provides one if no explicit constructor is defined
Initializes instance variables to default values:
Numeric: 0, Reference: null, Boolean: false
Defining your own constructor overrides default

38 / 81
Simple Constructor Example
// Box class with constructor
class Box {
double width, height, depth;

// Constructor
Box() {
[Link]("Constructing Box");
width = 10; height = 10; depth = 10;
}

// Compute volume
double volume() {
return width * height * depth;
}
}

class BoxDemo6 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();

[Link]("Volume is " + [Link]());


[Link]("Volume is " + [Link]());
}
} 39 / 81

Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Constructor Execution and Output
Program Output:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
What Happened:
Both mybox1 and mybox2 initialized by Box() constructor
Constructor called automatically when objects created
All boxes get same dimensions (10 × 10 × 10)
println() in constructor for illustration only
Understanding the new Operator:
new Box() is actually calling the Box() constructor
Parentheses after class name are constructor call
This explains why parentheses needed after class name
Box mybox1 = new Box(); creates and initializes object
Most constructors don’t display anything - they just initialize objects
40 / 81
Parameterized Constructors
Problem with Simple Constructor:
All boxes have same dimensions
Not flexible for real-world use
Need objects with different dimensions
Solution: Parameterized Constructor
// Box class with parameterized constructor
class Box {
double width, height, depth;

// Constructor with parameters


Box(double w, double h, double d) {
width = w; height = h; depth = d;
}

double volume() {
return width * height * depth;
}
}
Key Benefits:
Objects can have unique dimensions
Parameters provide initialization values
More flexible than fixed-dimension constructor
41 / 81
Using Parameterized Constructor

// Demo using parameterized Box constructor


class BoxDemo7 {
public static void main(String[] args) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

[Link]("Volume is " + [Link]());


[Link]("Volume is " + [Link]());
}
}

Program Output:

Volume is 3000.0
Volume is 162.0

What Happens:
Values passed to constructor: 10, 20, 15 → mybox1
Constructor copies them to width, height, depth
mybox1 dimensions become 10, 20, 15
Each object initialized as specified by constructor

42 / 81
Understanding the ’this’ Keyword
What is ’this’ ?
Keyword that refers to the object that invoked the current method
Always a reference to the current object
Can be used anywhere a reference to object of current class type is
permitted
Provides way for method to refer to invoking object

When to Use ’this’:


Sometimes method needs to refer to the object that invoked it
Useful for resolving naming conflicts
Helpful in certain programming situations
Can make code more explicit and clearer

Context Sensitivity:
this always refers to the invoking object within a method
Different objects calling same method get different this references
Each method invocation has its own this context
43 / 81
Basic this Usage Example

// Using ’this’ to refer to instance variables


Box(double w, double h, double d) {
[Link] = w;
[Link] = h;
[Link] = d;
}

Analysis:
Works same as version without this (redundant here)
Inside constructor, this always refers to invoking object
[Link] explicitly references object’s variable
When Redundant:
No naming conflicts
Context makes reference clear
Simple cases without ambiguity
When Useful:
Resolving parameter vs. instance variable conflicts
Making code explicit and self-documenting
Certain advanced programming scenarios
44 / 81
Instance Variable Hiding

The Problem:
Local variables (including parameters) can have same names as instance variables
Local variable ”hides” instance variable in its scope
Why Parameters Named Differently:
Earlier examples used different names (w, h, d) to avoid hiding
Using same names without this would refer to parameters
Two Solutions:
1 Use different parameter names
2 Use this to access instance variables explicitly
Programmer Preferences:
Some avoid hiding for clarity
Others use same names and resolve with this
Choice depends on style/team convention

45 / 81
Using ’this’ to Resolve Name Conflicts
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
How This Works:
Parameters named width, height, depth
Same names as instance variables
[Link] refers to instance variable
width (without this) refers to parameter
Assignment copies parameter value to instance variable
Benefits of This Approach:
Parameter names clearly indicate their purpose
More intuitive - width parameter sets width instance variable
Self-documenting code
Common in professional Java code 46 / 81

Caution:
Can be confusing initially
Requires careful attention to this usage
Easy to accidentally omit this and reference wrong variable
Memory Management in Java
The Question:
Objects dynamically allocated using new operator
How are objects destroyed and memory released?
What happens to memory when objects no longer needed?

Traditional Approach (C++):


Dynamically allocated objects must be manually released
Programmer responsible for calling delete operator
Manual memory management required
Risk of memory leaks and errors

Java’s Different Approach:


Java handles deallocation automatically
No need for explicit delete operations
Automatic memory management system
Technique called ”garbage collection”
47 / 81
How Garbage Collection Works
Basic Principle:
When no references to an object exist, object assumed no longer
needed
Memory occupied by object can be reclaimed
No need to explicitly destroy objects
System automatically handles cleanup

Garbage Collection Characteristics:


Occurs sporadically (if at all) during program execution
Will NOT occur simply because unused objects exist
Different Java runtime implementations use varying approaches
Generally transparent to programmer

Programmer Benefits:
No need to worry about memory deallocation in most cases
Reduces programming errors
Eliminates memory leaks from forgotten deallocations
Simplifies program development 48 / 81

When Objects Become Eligible:


All references to object set to null
References go out of scope
Object reassigned to reference another object
Practical Garbage Collection Example

Box b1 = new Box(); // Object created, b1 references it


Box b2 = new Box(); // Another object created, b2 references it

b1 = null; // First object eligible for GC


b2 = b1; // Second object eligible for GC

// Garbage collector may reclaim memory from unreferenced objects

Reference Lifecycle:
Objects exist while at least one reference points to them
Last reference removed → object eligible for GC
GC runs automatically; programmer cannot force it
Memory Management Strategy:
Create objects via new as needed
Use objects through references
Optionally set references to null when done
Rely on GC for cleanup

49 / 81
Garbage Collection Best Practices

Key Points:
GC is automatic; focus on proper object usage
Large-scale or memory-intensive apps need awareness
Avoid unnecessary object creation in loops
Set large object references to null when done
JVM handles memory efficiently; trust GC
Advanced Considerations:
GC algorithms and tuning differ across JVMs
Usually not needed for basic programming

50 / 81
Complete Class Example: Stack
Real-World Class Benefits:
Encapsulation of data and manipulation code
Methods define consistent, controlled interface
Internal details can change without affecting external code
Class acts like a ”data engine”

Stack Characteristics:
Stores data using first-in, last-out ordering
Like stack of plates - first down, last used
Two primary operations: push and pop
Push: Put item on top of stack
Pop: Take item from top of stack

Encapsulation Benefits:
Stack implementation details hidden from users
Could change from array to linked list without affecting interface
push() and pop() methods remain the same
Internal storage mechanism irrelevant to stack users 51 / 81
Stack Class Implementation

// Integer stack with max 10 items


class Stack {
int[] stck = new int[10];
int tos;

Stack() { tos = -1; }

void push(int item) {


if (tos == 9) [Link]("Stack full");
else stck[++tos] = item;
}

int pop() {
if (tos < 0) { [Link]("Stack underflow"); return 0; }
else return stck[tos--];
}
}

52 / 81
Stack Class Analysis
Class Components:
Data: stck array (holds integers), tos variable (top of stack index)
Constructor: Stack() initializes tos to -1 (empty stack)
Methods: push() and pop() for stack operations
Method Details:
push(): Adds item if stack not full, otherwise shows error
pop(): Removes and returns top item if stack not empty
Error handling built into both methods
Encapsulation Success:
Stack held in array, but this detail hidden from users
Users only interact through push() and pop()
Internal representation could change without affecting interface
Could use linked list, different array size, etc.
Key Insight:
Interface (methods) remains constant
Implementation details can vary
This is power of object-oriented programming 53 / 81
Using the Stack Class
class TestStack {
public static void main(String[] args) {
Stack s1 = new Stack();
Stack s2 = new Stack();
for(int i=0;i<10;i++) [Link](i);
for(int i=10;i<20;i++) [Link](i);

[Link]("Stack in s1:");
for(int i=0;i<10;i++) [Link]([Link]());

[Link]("Stack in s2:");
for(int i=0;i<10;i++) [Link]([Link]());
}}
/* Output:
Stack in s1: Stack in s2:
9 19
8 18
7 17
6 16
5 15
4 14
3 13
2 12
1 11
0 10 54 / 81
*/

You might also like