0% found this document useful (0 votes)
2 views52 pages

OPP Module 2

The document outlines the fundamentals of Object-Oriented Programming (OOP) with Java, focusing on classes, methods, and object creation. It explains the structure and purpose of classes, how to declare and instantiate objects, and the significance of methods in manipulating data within classes. Additionally, it covers concepts such as method overloading, parameter passing, and encapsulation, providing examples to illustrate these principles.

Uploaded by

Abubaker osman
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)
2 views52 pages

OPP Module 2

The document outlines the fundamentals of Object-Oriented Programming (OOP) with Java, focusing on classes, methods, and object creation. It explains the structure and purpose of classes, how to declare and instantiate objects, and the significance of methods in manipulating data within classes. Additionally, it covers concepts such as method overloading, parameter passing, and encapsulation, providing examples to illustrate these principles.

Uploaded by

Abubaker osman
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

OPP’s WITH JAVA BCS306A

OPP’s WITH JAVA

MODULE -2

SL Topics Page No
NO

1 Introducing Classes: Class Fundamentals, Declaring Objects, Assigning 1-7


Object Reference Variables,

2 Introducing Methods, Constructors, This Keyword, Garbage Collection.


8-25
3 Methods and Classes: Overloading Methods, Objects as Parameters, 26-36
Argument Passing, Returning Objects,
4 Recursion, Access Control, Understanding static, Introducing final,
Introducing Nested and Inner Classes. 37-52

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


1
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

MODULE-02

INTRODUCING CLASSES

Introducing Classes:

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. As such,
the class forms the basis for object-oriented programming in Java. Any concept
you wish to implement in a Java program must be encapsulated within a class.

Class Fundamentals

Perhaps the most important thing to understand about a class is that it defines a new
data type. Once defined, this new type can be used to create objects of that type. Thus,
a class is a template for an object, and an object is an instance of a class. Because
an object is an instance of a class, you will often see the two words object and instance
used interchangeably.

The General Form of a Class

A class is declared by use of the class keyword. The classes that have been used up
to this point are actually very limited examples of its complete form. Classes can (and
usually do) get much more complex. A simplified general form of a class definition is
shown here:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


2
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. Variables defined within a class are called instance variables.


2. The code inside a class is contained within methods.
3. Both methods and variables are collectively called members of the class.
4. Methods act upon and access the instance variables.
5. Each object (instance) of a class has its own copy of instance variables.
6. Data of one object is separate and unique from another object.
7. All methods follow the same general form as main(), but most are not static
or public.
8. A class does not need to have a main() method unless it’s the program’s
starting point.
9. Some Java applications do not require a main() method at all.

A Simple Class

Here is a class called Box that defines three instance variables: width, height, and
depth. Currently, Box does not contain any methods (but some will be added soon).

1. A class defines a new data type (e.g., Box).


2. The class declaration is only a template; it does not create an object.
3. To create an object, use:
Box mybox = new Box();
4. After execution, mybox refers to an instance of the class Box.
5. Each object (instance) has its own copy of all instance variables.
6. For Box, each object has its own width, height, and depth.
7. The dot (.) operator is used to access an object’s members (variables and
methods).
8. Example: [Link] = 100;
9. The statement assigns the value 100 to the width variable of the object mybox.
10. The dot operator (.) is formally categorized as a separator in Java.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


3
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. The file name should be [Link] because the main() method is in the
BoxDemo class.
2. When compiled, two .class files are created — one for Box and one for
BoxDemo.
3. The Java compiler automatically places each class into its own .class file.
4. It’s not required for both classes to be in the same source file.
5. You can have [Link] and [Link] separately.
6. To run the program, execute [Link].
7. Output of the program:
Volume is 3000.0
8. Each object has its own copy of instance variables (depth, width, height).
9. Changes in one object’s variables do not affect those of another object.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


4
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

The output produced by this program is shown here:

Volume is 3000.0

Volume is 162.0

As you can see, mybox1’s data is completely separate from the data contained in
mybox2.

Declaring Objects

1. Creating a class defines a new data type.


2. Declaring objects of a class is a two-step process:
o Step 1: Declare a reference variable of the class type.
o Step 2: Create (allocate) the object using the new operator.
3. Example:
4. Box mybox = new Box();

can be written as:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


5
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Box mybox; // declare reference to object

mybox = new Box(); // allocate a Box object

5. The first line creates a reference variable but no object yet.


6. The second line allocates memory for the object and assigns its reference to the
variable.
7. The new operator dynamically allocates memory at runtime.
8. The reference returned by new is stored in the variable, which holds the
memory address of the object.
9. In Java, all class objects are dynamically allocated using new.

A Closer Look at new

a. The new operator dynamically allocates memory for an object.


b. General form: class-var = new classname();
c. class-var → variable of the class type.
d. classname() → calls the constructor of the class.
e. A constructor defines what happens when an object is created.
f. Most classes explicitly define their own constructors.
g. If no constructor is defined, Java automatically provides a default
constructor.
h. In the Box example, the default constructor is used.
i. You can later define your own constructors for custom initialization.

1. Primitive types (e.g., int, char) do not use new because they are not objects.
2. Primitive types are implemented as normal variables for efficiency.
3. Objects have extra features and overhead, so primitives are kept lightweight.
4. Java provides object versions of primitive types (wrapper classes) when full
objects are needed.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


6
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

5. The new operator allocates memory at runtime for objects.


6. This allows programs to create objects dynamically as needed.
7. If there’s not enough memory, new throws a runtime exception.

1. Class vs Object:

Class: Logical construct (template or blueprint).

Object: Physical entity (occupies memory).

2. When an object is declared, it becomes an instance of the class.


3. Always remember: Class = definition, Object = actual instance in memory.

Assigning Object Reference Variables

Assigning one object reference to another does not create a new object.

o Example:

Box b1 = new Box();

Box b2 = b1;

➢ Both b1 and b2 refer to the same object.


o No new memory is allocated — only the reference (address) is copied.
o Changes made through one reference affect the same underlying object.
o b1 and b2 are independent references, but point to the same object.
o If b1 is later reassigned or set to null, it does not affect b2.
➢ b1 = null; // b2 still refers to the object
o Key idea: Object references are copied, not the actual objects.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


7
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Introducing Methods

A class usually contains instance variables and methods.

Methods provide functionality and control how data is used within a class.

General form of a method:

type name(parameter-list) {

// body of method

a. type → the data type returned by the method (can be primitive or class
type).
b. If no value is returned, use void as the return type.
c. name → the method name, must be a valid identifier.

parameter-list → a list of type and variable pairs separated by commas.

Example: (int a, int b)

If a method has no parameters, the list is empty: ().

Methods that return a value use the return statement:

return value;

Java allows methods to take parameters, return values, or do both —


providing great flexibility.

Adding a Method to the Box Class

a. It’s possible to create a class with only data, but this is rare in practice.
b. Usually, methods are used to access and manipulate instance
variables.
c. Methods define the interface of a class — how other parts of a
program interact with it.
d. This allows data hiding — internal details are hidden behind clean
method abstractions.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


8
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

A class can have methods that are:

Public – accessed externally.

Internal (private) – used only within the class.

In the Box example, it’s better to compute the volume inside the Box class itself.
This improves encapsulation — keeping behavior (methods) and data (variables)
together.

Example (conceptually):
class Box {
double width, height, depth;
double volume() {
return width * height * depth;
}
}

Now, the Box class itself handles the volume calculation instead of BoxDemo.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


9
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

[Link]() calls the volume() method for the mybox1 object.

The dot (.) operator is used to invoke a method on a specific object.

[Link]() → displays volume of mybox1.


[Link]() → displays volume of mybox2.

Each time volume() is called, it operates on the specific object that invoked it.

1. When a method is called, control transfers to that method’s code.

2. After execution, control returns to the calling code.

3. Methods in Java are essentially subroutines or functions associated with


classes.

4. Inside the volume() method, instance variables (width, height, depth) are
accessed directly —
no need for [Link] or the dot operator.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


10
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

5. This is because a method is always executed relative to the object that


invoked it.

6. Therefore, within a class’s own method:

7. Instance variables and methods are implicitly linked to the current object.

8. Rule recap:

Access from outside the class → use object name + dot operator.

Access from inside the class → use the variable or method name directly.

Returning a Value

1. The previous volume() method displayed the volume directly, which is not
always ideal.

2. Sometimes, other parts of the program may need the volume value without
displaying it.

3. A better approach is to have volume() compute the volume and return it.

4. The method should use a return type (e.g., double) instead of void.

5. Example improved volume() method:

6. double volume() {
return width * height * depth;
}
7. This allows the caller to use the returned value as needed, for example:

double vol = [Link]();

8. Returning values makes methods more flexible and reusable.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


11
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. A method that returns a value can be used on the right side of an assignment.

Example: vol = [Link]();

2. Here, vol receives the value returned by volume().

3. Returned value must match the method’s return type.

4. Example: A method with boolean return type cannot return an integer.

5. The receiving variable must also be compatible with the method’s return type.

6. You can use the returned value directly without an intermediate variable:

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

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


12
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

7. This approach makes the code more concise and efficient.

Adding a Method That Takes Parameters

1. While some methods don’t need parameters, most do.

2. Parameters allow a method to be generalized.

3. A parameterized method can operate on a variety of data or be used in slightly


different situations.

4. Example of a method returning the square of 10:

int square() {
return 10 * 10;
}
5. This method does return 10², but its use is very limited.

6. Making the method parameterized improves usability:

int square(int i) {
return i * i;
}
7. Now square() can return the square of any integer, not just 10.

8. Example calls:

int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
9. Explanation of calls:

First call → parameter i receives 5.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


13
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Second call → i receives 9.


Third call → i receives the value of y, which is 2.
10. Key idea: square() returns the square of whatever value it is passed.

11. Important distinction:

Parameter → variable defined by a method that receives a value (e.g., i).


Argument → value passed to the method when invoked (e.g., 100 in
square(100)).
12. Improving the Box class:

Previously, dimensions were set individually:

[Link] = 10;
[Link] = 20;
[Link] = 15;
13. Problems:

A. Clumsy and error-prone (easy to forget a dimension).


B. In well-designed Java programs, instance variables should only be
accessed through methods.
C. You can change a method’s behavior, but not an exposed variable’s
behavior.
D. Better approach: create a method that takes box dimensions as
parameters and sets instance variables.
E. This concept is implemented in a program using a parameterized
method to initialize the box dimensions.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


14
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d.


Inside setDim( ) the values of w, h, and d are then assigned to width, height, and depth,
respectively.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


15
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Constructors

1. Initializing all variables in a class for each instance can be tedious.

2. Even with convenience methods like setDim(), it’s simpler to initialize the
object when it is first created.

3. Java allows automatic initialization of objects at creation through a


constructor.

4. A constructor initializes an object immediately upon creation.

5. It has the same name as the class in which it resides.

6. It is syntactically similar to a method.

7. The constructor is automatically called when the object is created, before the
new operator completes.

8. Constructors have no return type, not even void.

9. Implicitly, the constructor’s return type is the class type itself.

10. The job of a constructor is to initialize the internal state of an object, providing
a fully initialized, usable object immediately.

11. The Box example can be improved by using a constructor instead of setDim().

12. This allows the dimensions of a box to be automatically initialized when the
object is constructed.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


16
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

a. Both mybox1 and mybox2 were initialized by the Box() constructor


when created.

b. Since the constructor sets the same dimensions (10 × 10 × 10), both
objects have the same volume.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


17
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

c. The println() statement inside the constructor is for illustration only;


most constructors do not display anything.

d. Constructors simply initialize objects.

1. Reexamining the new operator:

2. General form:

class-var = new classname();

3. The parentheses after the class name are needed because the constructor is
being called.

4. Example: Box mybox1 = new Box(); → new Box() calls the Box() constructor.

5. If a class does not have an explicit constructor, Java provides a default


constructor.

6. Using the default constructor:

7. Uninitialized instance variables get default values:

a. Numeric types → 0

b. Reference types → null

c. Boolean → false

8. The default constructor is sufficient for simple classes.

9. For more sophisticated classes, you need to define your own constructor.

10. Once a custom constructor is defined, the default constructor is no longer


used.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


18
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Parameterized Constructors

a. The previous Box() constructor initializes all boxes with the same
dimensions, which is not very useful.
b. A way is needed to create Box objects with different dimensions.
c. The solution is to add parameters to the constructor.
d. A parameterized constructor allows the dimensions of a box to be set at
creation time.
e. This approach makes the constructor much more useful and flexible.
f. When using a parameterized constructor, Box objects are created by
passing values for the dimensions during instantiation.
g. Example usage (conceptual):
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(5, 5, 5);
h. This allows each object to have its own specific width, height, and depth.
i. Key idea: Parameterized constructors combine initialization and creation
in a single, convenient step

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


19
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

The this Keyword

1. this keyword: Used inside a method to refer to the current object that invoked
the method.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


20
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

2. this can be used anywhere a reference to an object of the current class is


allowed.

3. Example of this in a Box constructor (redundant use):

4. Box(double w, double h, double d) {


[Link] = w;
[Link] = h;
[Link] = d;
}
o Works exactly like the earlier version without this.

o this always refers to the object invoking the constructor.

5. this is redundant here but useful in other contexts.

Instance Variable Hiding:

Local variables cannot have duplicate names in the same or enclosing scopes.
However, local variables or parameters can have the same name as instance
variables.
When this happens, the local variable hides the instance variable.

• Example: if constructor parameters were named width, height, depth, they would
hide the instance variables.

To resolve this, this is used to refer explicitly to instance variables.

Example using this to resolve naming collision:

Box(double width, double height, double depth) {


[Link] = width;
[Link] = height;
[Link] = depth;
}

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


21
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Caution:

o Using this in such cases can be confusing.

o Some programmers avoid reusing names for clarity.

o Others use the same names for parameters and rely on this to access
instance variables.

It’s a matter of coding style or taste which approach to adopt.

Garbage Collection

1. Objects are dynamically allocated using the new operator.

2. Question arises: how are objects destroyed and memory released?

3. In languages like C++, dynamically allocated objects must be manually


released using delete.

4. Java handles deallocation automatically.

5. This process is called garbage collection.

6. Garbage collection works as follows:

o When no references exist to an object, it is assumed no longer needed.

o The memory occupied by that object can then be reclaimed.

7. There is no need to explicitly destroy objects in Java.

8. Garbage collection occurs sporadically, not immediately when objects become


unreferenced.

9. Different Java run-time implementations may use varying approaches to


garbage collection.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


22
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

10. Generally, programmers do not need to worry about garbage collection when
writing Java programs.

A Stack Class

1. The Box class is useful to illustrate class elements but has little practical value.

2. To demonstrate the real power of classes, a more sophisticated example will


be used.

3. Object-Oriented Programming (OOP) benefits include encapsulation of data


and the code that manipulates it.

4. In Java, classes achieve encapsulation.

5. Creating a class defines a new data type that specifies:

o The nature of the data being manipulated.

o The routines/methods used to manipulate the data.

6. Methods provide a controlled interface to the class’s data.

7. You can use the class through its methods without worrying about internal
details or data management.

8. A class acts like a “data engine”:

o You don’t need to know what happens inside.

o Internal workings can change without affecting outside code, as long as


the interface (methods) remains consistent.

9. Practical example: a stack.

10. A stack stores data in first-in, last-out (FILO) order, like a stack of plates.

11. Stack operations:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


23
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

o Push: add an item on top of the stack.

o Pop: remove an item from the top of the stack.

12. The entire stack mechanism can be easily encapsulated using a class.

1. The Stack class defines:


Two data items
Two methods
A constructor
2. The stack of integers is stored in the array stck.
3. The array is indexed by tos, which contains the index of the top of the stack.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


24
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

4. The Stack() constructor initializes tos to –1, indicating an empty stack.


5. The push() method adds an item to the stack.
6. The pop() method retrieves an item from the stack.
7. Access to the stack is only through push() and pop(), so the internal storage
(array) is irrelevant to the user.
8. The stack could be implemented using other data structures, e.g., a linked list,
without changing the interface.
9. The TestStack class demonstrates usage:
10. Creates two integer stacks
11. Pushes values onto each stack
12. Pops values from each stack

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


25
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

A Closer Look at Methods and Classes

1. In Java, two or more methods in the same class can share the same name if
their parameter declarations differ.

2. Such methods are called overloaded methods.

3. The process of defining them is called method overloading.

4. Method overloading is one way Java supports polymorphism.

5. Overloading may seem unusual if you haven’t used languages that allow
it, but it is powerful and useful in Java.

6. When an overloaded method is called, Java determines which version to


execute based on the type and/or number of arguments.

7. Overloaded methods must differ in type and/or number of parameters.

8. Overloaded methods may have different return types, but return type alone
cannot distinguish them.

9. Java executes the version of the method whose parameters match the
arguments used in the call.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


26
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. The method test() is overloaded four times.

2. Versions of test():

First: takes no parameters

Second: takes one integer parameter

Third: takes two integer parameters

Fourth: takes one double parameter


DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF
27
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

3. The return type of a method (e.g., the fourth version returning a value)
does not affect overloading.

4. When an overloaded method is called, Java looks for a match between


arguments and parameters.

5. The match does not always have to be exact.

6. Java’s automatic type conversions can sometimes affect overload


resolution.

1. If a method like test(int) is not defined, calling test() with an integer


argument finds no exact match.

2. Java can automatically convert an integer to a double, so test(double) is


called instead.

3. If test(int) had been defined, it would be called instead of converting.


DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF
28
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

4. Java uses automatic type conversions only if no exact match exists.

5. Method overloading supports polymorphism by implementing “one


interface, multiple methods”.

6. Languages without overloading require unique names for each method


version.

7. Example in C:

abs() → absolute value of an integer

labs() → absolute value of a long

fabs() → absolute value of a floating-point value

8. In Java, the same method name (e.g., abs()) can be used for different
numeric types.

9. Java determines which version of abs() to call based on the argument type.

[Link] of overloading: related methods can use a common name,


simplifying usage.

[Link] compiler selects the correct version; the programmer only needs to
remember the general operation.

[Link] reduces multiple names into one through polymorphism.

[Link] overloaded method can perform any action; there is no strict rule
requiring them to be related.

[Link] guideline: overloaded methods should perform closely related


operations.

[Link] of misuse:

[Link] sqr for integer square and floating-point square root is confusing.

[Link] practice: overload only closely related operations to preserve


clarity and purpose.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


29
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Overloading Constructors

1. The Box() constructor requires three parameters.

2. All declarations of Box objects must pass three arguments.

3. Example of an invalid statement:

Box ob = new Box(); → Error because three arguments are required.

4. Questions raised by this limitation:

5. What if you want a box but don’t know or care about its initial
dimensions?

6. What if you want to initialize a cube using one value for all three
dimensions?

7. The current Box class does not allow these options.

8. Solution: overload the Box constructor to handle these cases.

9. An improved version of Box can provide multiple constructors to support


different initialization scenarios.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


30
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


31
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Using Objects as Parameters

1. The equalTo() method compares two objects for equality and returns a
boolean result.
2. It compares the invoking object with the object passed as a parameter.
3. If both objects contain the same values, equalTo() returns true; otherwise,
it returns false.
4. The parameter o in equalTo() is of type Test (a user-defined class).
5. Class types can be used like built-in Java types.
6. One common use of object parameters is in constructors.
7. Often, you may want to construct a new object identical to an existing
object.
8. To achieve this, define a constructor that takes an object of the class as a
parameter.
9. Example: A version of Box that allows one object to initialize another.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


32
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


33
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

A Closer Look at Argument Passing


1. There are two ways a language can pass arguments to a subroutine: call-
by-value and call-by-reference.
2. Call-by-value:
a. Copies the value of an argument into the formal parameter.
b. Changes made to the parameter do not affect the original argument.
3. Call-by-reference:
a. Passes a reference to the argument, not its value.
b. Changes made to the parameter affect the original argument.
4. Java uses call-by-value for all arguments, but behavior differs for
primitive and reference types.
5. When passing a primitive type to a method:
6. The value is copied.
7. Changes to the parameter do not affect the original argument.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


34
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. Operations inside meth() do not affect the values of primitive variables a


and b used in the call.
2. When passing an object to a method, behavior changes because objects are
effectively passed by reference.
3. A variable of a class type is a reference to an object, not the object itself.
4. Passing this reference to a method means the parameter refers to the
same object as the argument.
5. Effectively, objects behave as if passed by call-by-reference.
6. Changes to the object inside the method will affect the original object
used as the argument.
7. Example programs illustrate this behavior with objects.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


35
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Returning Objects
1. A method can return any type of data, including user-defined class types.
2. Example: The incrByTen() method returns an object.
3. In the returned object, the value of a is ten greater than in the invoking object.

1. Each time incrByTen() is invoked, a new object is created.


2. A reference to this new object is returned to the calling routine.
3. Since all objects are dynamically allocated using new, objects do not go out
of scope when the method that created them terminates.
4. The object continues to exist as long as there is a reference to it in the program.
5. When no references exist, the object will be reclaimed by garbage collection.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


36
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Recursion
1. Recursion in Java allows a method to call itself.
2. A method that calls itself is called a recursive method.
3. Classic example: computing factorial of a number.
4. Factorial of N is the product of all whole numbers from 1 to N.
5. Example: 3! = 1 × 2 × 3 = 6.
6. Factorial can be computed using a recursive method.

1. How the fact() method works


• Base case: If fact(1) is called, it simply returns 1.
• Recursive case: For n > 1, fact(n) returns fact(n-1) * n.
• Each call reduces n by 1 until it reaches 1, then the calls start returning back up
the chain.

2. Example: fact(3)
• First call: fact(3) → calls fact(2)
• Second call: fact(2) → calls fact(1)
• Third call: fact(1) → returns 1 (base case)
• Returning back:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


37
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

o Second call multiplies 1 × 2 → returns 2


o First call multiplies 2 × 3 → returns 6
So, fact(3) = 6.

3. Stack behavior in recursion


• Each recursive call allocates new local variables and parameters on the stack.
• As calls return, these variables are removed from the stack.
• This “telescoping” effect allows recursion to keep track of intermediate results.

4. Performance and limits


• Recursive methods can be slightly slower than iterative methods due to
overhead.
• Too many recursive calls can exhaust the stack, causing a runtime exception.
• Base cases are crucial. Without a base case, recursion never stops, leading to
infinite recursion.

5. Advantages of recursion
• Simplifies complex algorithms like QuickSort or AI algorithms.
• Makes some algorithms easier to read and implement than iterative versions.

6. Important tips
• Always include a base case (if statement) to stop recursion.
• Use println() statements during debugging to see the flow of recursive calls.

7. Another example: printArray()


• Recursive methods are not limited to numbers.
• printArray() can recursively print the first i elements of an array.
• Each call handles one element and then calls itself for the remaining elements,
eventually reaching the base case.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


38
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Introducing Access Control

1. Encapsulation links data with the code that manipulates it.


2. Encapsulation provides another important attribute: access control.
3. Through encapsulation, you can control what parts of a program can access the
members of a class.
4. By controlling access, you can prevent misuse.
5. For example, allowing access to data only through a well-defined set of methods,
you can prevent the misuse of that data.
6. When correctly implemented, a class creates a “black box” which may be used,
but the inner workings of which are not open to tampering.
7. However, the classes presented earlier do not completely meet this goal.
8. For example, consider the Stack class shown at the end of Chapter 6.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


39
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

9. While it is true that the methods push() and pop() do provide a controlled
interface to the stack, this interface is not enforced.
10. It is possible for another part of the program to bypass these methods and access
the stack directly.
11. In the wrong hands, this could lead to trouble.
12. Java provides a mechanism by which you can precisely control access to the
various members of a class.
13. How a member can be accessed is determined by the access modifier attached
to its declaration.
14. Java supplies a rich set of access modifiers.
15. Some aspects of access control are related mostly to inheritance or packages.
16. (A package is, essentially, a grouping of classes.)
17. These parts of Java’s access control mechanism will be discussed in subsequent
chapters.
18. Here, let’s begin by examining access control as it applies to a single class.
19. Once you understand the fundamentals of access control, the rest will be easy.
20. NOTE: The modules feature added by JDK 9 can also impact accessibility.
Modules are described in Chapter 16.
21. Java’s access modifiers are public, private, and protected.
22. Java also defines a default access level.
23. protected applies only when inheritance is involved.
24. The other access modifiers are described next.
25. Public and Private:
26. When a member of a class is modified by public, then that member can be
accessed by any other code.
27. When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
28. Now you can understand why main() has always been preceded by the public
modifier.
29. It is called by code that is outside the program—that is, by the Java run-time
system.
30. When no access modifier is used, then by default:
31. The member of a class is public within its own package, but cannot be accessed
outside of its package.
32. (Packages are discussed in Chapter 9.)
33. In the classes developed so far, all members of a class have used the default
access mode.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


40
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

34. Usually, you will want to restrict access to the data members of a class,
allowing access only through methods.
35. There will be times when you will want to define methods that are private to a
class.
36. An access modifier precedes the rest of a member’s type specification.

Inside the Test class:


a uses default access, which in this example is the same as specifying public.
b is explicitly specified as public.
c is given private access.
This means it cannot be accessed by code outside of its class.
Inside the AccessTest class:
a. cannot be used directly.
[Link] be accessed through its public methods: setc() and getc().

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


41
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

If you were to remove the comment symbol from the following line:
// ob.c = 100; // Error!
The program would not compile because of the access violation.

1. Now both stck (which holds the stack) and tos (the index of the top of the stack)
are specified as private.
2. This means they cannot be accessed or altered except through push() and pop().
3. Making tos private prevents other parts of the program from inadvertently setting
it to a value beyond the end of the stck array.
4. The following program demonstrates the improved Stack class.
5. Try removing the commented-out lines to prove that stck and tos members are
inaccessible.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


42
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. Although methods usually provide access to the data defined by a class, this does
not always have to be the case.
2. It is perfectly proper to allow an instance variable to be public when there is
good reason to do so.
3. For example, most of the simple classes in this book were created with little
concern about controlling access to instance variables for simplicity.
4. In most real-world classes, operations on data should be allowed only through
methods.
5. The next chapter will return to the topic of access control.
6. Access control is particularly important when inheritance is involved.

Understanding static
1. Sometimes you may want to define a class member that is used independently
of any object of that class.
2. Normally, a class member must be accessed in conjunction with an object of
its class.
3. It is possible to create a member that can be used by itself, without reference to
a specific instance.
4. To create such a member, precede its declaration with the keyword static.
5. When a member is declared static:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


43
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

a. It can be accessed before any objects of its class are created.


b. It can be accessed without reference to any object.
c. Both methods and variables can be declared static.
6. The most common example of a static member is main().
7. main() is declared static because it must be called before any objects exist.
8. Instance variables declared as static are essentially global variables.
9. When objects of the class are created, no copy of a static variable is made.
10. Instead, all instances of the class share the same static variable.

Methods declared as static have several restrictions:


• They can only directly call other static methods of their class.
• They can only directly access static variables of their class.
• They cannot refer to this or super in any way.

Here is the output of the program:


Static block initialized.
x = 42
a=3
b = 12
1. As soon as the UseStatic class is loaded, all of the static statements are run.
2. First, a is set to 3.
3. Then the static block executes:

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


44
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

a. It prints a message.
b. Initializes b to a * 4, which is 12.
4. Then main() is called, which calls meth(), passing 42 to x.
5. The three println() statements refer to:
6. The two static variables a and b.
7. The parameter x.

1. Outside of the class in which they are defined, static methods and variables
can be used independently of any object.
2. To do so, specify the name of their class followed by the dot operator.
3. Example: To call a static method from outside its class, use the general form:
a. [Link]()
b. Here, classname is the name of the class in which the static method is
declared.
4. This format is similar to calling non-static methods through object-reference
variables.
5. A static variable can be accessed in the same way—by use of the dot operator
on the name of the class.
6. This is how Java implements a controlled version of global methods and
global variables.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


45
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Introducing final

1. A field can be declared as final.


2. Doing so prevents its contents from being modified, making it essentially a
constant.
3. This means that you must initialize a final field when it is declared.
4. You can do this in one of two ways:
5. Give it a value when it is declared.
6. (Second method not shown here but commonly done in constructors — implied
from the text).
7. Example:
a. final int FILE_NEW = 1;
b. final int FILE_OPEN = 2;
c. final int FILE_SAVE = 3;
d. final int FILE_SAVEAS = 4;
e. final int FILE_QUIT = 5;
8. Subsequent parts of your program can now use FILE_OPEN, etc., as if they were
constants, without fear that a value has been changed.
9. It is a common coding convention to choose all uppercase identifiers for final
fields, as the example shows.
10. In addition to fields, both method parameters and local variables can be
declared final.
11. Declaring a parameter final prevents it from being changed within the method.
12. Declaring a local variable final prevents it from being assigned a value more
than once.
13. The keyword final can also be applied to methods, but its meaning is
substantially different than when applied to variables.
14. This additional usage of final is explained in the next chapter, when inheritance
is described.

Arrays Revisited
1. Arrays were introduced earlier in this book, before classes had been discussed.
2. Now that you know about classes, an important point can be made about arrays:
they are implemented as objects.
3. Because of this, there is a special array attribute that you will want to take
advantage of.
4. Specifically, the size of an array—that is, the number of elements that an array
can hold—is found in its length instance variable.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


46
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

5. All arrays have this variable, and it will always hold the size of the array.

• The size of each array is displayed.


• Keep in mind that the value of length has nothing to do with the number of
elements actually in use.
• It only reflects the number of elements that the array is designed to hold.
• You can put the length member to good use in many situations.
• Example: an improved version of the Stack class.
o The earlier versions of this class always created a ten-element stack.
o The following version lets you create stacks of any size.
o The value of [Link] is used to prevent the stack from overflowing.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


47
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


48
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Introducing Nested and Inner Classes


It is possible to define a class within another class; such classes are known as nested
classes.

1. The scope of a nested class is bounded by the scope of its enclosing class.

2. If class B is defined within class A, then B does not exist independently of A.

3. A nested class has access to the members (including private members) of


the class in which it is nested.

4. However, the enclosing class does not have access to the members of the
nested class.

5. A nested class that is declared directly within its enclosing class scope is a
member of its enclosing class.

6. It is also possible to declare a nested class that is local to a block.

7. There are two types of nested classes:

8. Static nested class

a. Has the static modifier applied.

b. Because it is static, it must access the non-static members of its


enclosing class through an object.

c. It cannot refer to non-static members directly.

9. Inner class (non-static nested class)

a. Has access to all variables and methods of its outer class.

b. May refer to them directly, like other non-static members of the outer
class.

10. The following program illustrates how to define and use an inner class.

a. The class named Outer has:

b. One instance variable named outer_x.

c. One instance method named test().

d. Defines one inner class called Inner.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


49
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

Output from this application is shown here:

display: outer_x = 100

1. In the program, an inner class named Inner is defined within the scope of
class Outer.

2. Therefore, any code in class Inner can directly access the variable outer_x.

3. An instance method named display() is defined inside Inner.

4. This method displays outer_x on the standard output stream.

5. The main() method of InnerClassDemo:

6. Creates an instance of class Outer.

7. Invokes its test() method.

8. The test() method creates an instance of class Inner, and the display() method
is called.

9. It is important to realize that an instance of Inner can be created only in the


context of class Outer.

10. The Java compiler generates an error message otherwise.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


50
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

11. In general, an inner class instance is often created by code within its
enclosing scope, as shown in the example.

12. An inner class has access to all members of its enclosing class, but the
reverse is not true.

13. Members of the inner class are known only within the scope of the inner
class and may not be used by the outer class.

14. For example,

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


51
TECHNOLOGY (KNSIT), BENGALURU
OPP’s WITH JAVA BCS306A

1. Although we have been focusing on inner classes declared as members


within an outer class scope, it is also possible to define inner classes within
any block scope.

2. For example, you can define a nested class within the block defined by a
method or even within the body of a for loop.

3. The next program demonstrates this concept.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING (AIML)KNS INSTITUTE OF


52
TECHNOLOGY (KNSIT), BENGALURU

You might also like