Java Object-Oriented Programming Basics
Java Object-Oriented Programming Basics
MODULE-2
CHAPTER-1
INTRODUCING CLASSES
Chapter Contents:
• Introducing Classes
Class Fundamentals, Declaring Objects, Assigning Object
Reference Variables, Introducing Methods, Constructors,
The this Keyword, Garbage Collection.
• Textbook: Chapter 6
Objects and Classes in Java
An object in Java is the physical as well as a logical
entity, whereas, a class in Java is a logical entity
only.
An entity that has state and behavior is known as an
object e.g., chair, bike, pen, table, car, etc.
It can be physical or logical (tangible and intangible).
The example of an intangible object is the banking
system.
an object consists of :
State : It is represented by attributes of an object. It
also reflects the properties of an object.
Behavior : It is represented by methods of an object.
It also reflects the response of an object with other
objects.
Identity : An object identity is typically implemented
via a unique ID.
•The value of the ID is not visible to the external user.
However, it is used internally by the JVM to identify
each object uniquely.
Contd..
type variable1; }
} }
}
returnType methodName2(parameters) {
// method body
}
}
Contd..
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class are called
members of the class.
Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy of
these variables.
A Simple Class (Box Class)
Define a class called Box that defines three instance variables:
width, height, and depth.
Currently, Box does not contain any methods.
class Box {
double width;
double height;
double depth;
}
This class defines a new data type called Box. Use this name to declare objects of
type Box.
OBJECT CREATION
Example:
•Assign the width variable of mybox the value 100.
[Link] = 100;
•This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100.
•In general, you use the dot operator to access both the instance variables and the methods within an object.
DECLARING AN OBJECT
Obtaining objects of a class is a two-step process.
[Link] a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
[Link] an actual, physical copy of the object and assign it to
that variable. You can do this using the new operator.
•The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it. This reference is, essentially, the address in memory
of the object allocated by new.
•This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Example:
Step-1: Box mybox; // declare reference to object
Here, class-var is a variable of the class type being created. The classname is the name
of the class that is being instantiated.
The class name followed by parentheses specifies the constructor for the class.
A constructor defines what occurs when an object of a class is created (especially
initialization of instance variables).
The new operator dynamically allocates memory for an object.
The advantage is that:
The program can create as many or as few objects as it needs during the execution of
your
program (Memory is finite and new may not be able to allocate memory because
insufficient memory exists).
Object Reference Variables
Consider the statements:
Box b1 = new Box();
Box b2 = b1;
The assignment of b1 to b2 did not allocate any
memory or copy any part of the original object. Although b1 and b2 both refer to the
It simply makes b2 refer to the same object as same object, they are not linked in any
does b1. other way.
•After this fragment executes, b1 and b2 will both A subsequent assignment to b1 will simply
refer to the same object. unhook b1 from the original object without
•Thus, any changes made to the object through affecting the object or affecting b2.
b2 will affect the object to which b1 is referring,
since they are the same object.
Consider the statements:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
This demonstrates that object references in Java are independent — changing one reference
doesn't affect others pointing to the same object unless you modify the object itself.
INTRODUCING METHODS
double width;
}
Main Method
}
•The statement [Link](); invokes the volume() method on mybox1. That is, it calls volume()
relative to the mybox1 object, using the object’s name followed by the dot operator.
•Thus, the call to [Link]() displays the volume of the box defined by mybox1.
Introducing methods contd..
Returning a Value
•A better way to implement volume() is to compute the volume of the box and return the result to the caller.
•This makes the volume available to other parts of the program.
Example:
class Calculator {
// Method with return type Output:
Square of 5 is: 25
int square(int number) {
return number * number;
}
}
public class SquareDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
int input = 5;
int result = [Link](input);
[Link]("Square of " + input + " is: " + result);
}
}
Methods with parameters
•Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of
data and/or be used in a number of slightly different situations.
•It is important to keep the two terms: parameter and argument straight.
A parameter is a variable defined by a method that receives a value when the method is called.
•An argument is a value that is passed to a method when it is invoked.
Example:
int x, y; Argum
ent
x = square(5);
int square(int i) { Pa
return i * i; ra me
} ter
Methods with parameters
Example:
public class Greeting {
void sayHello(String name) { // Method that takes a parameter and prints a
greeting message
[Link]("Hello, " + name + "!");
}
public static void main(String[] args) {
Greeting greet = new Greeting(); // Create an object of Greeting class
output
Hello, Ram!
Hello, Raj!
.
Constructors
1. Default Constructor
A constructor without any parameters.
If you don’t write any constructor, Java automatically provides a default one.
public class Student {
String name;
int age;
Student() { // Default Constructor
name = "Unknown";
age = 0; output
}
void display() { Unknown - 0
[Link](name + " - " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
[Link]();
}
}
Types of Constructor
} }
Output
Bob - 22
The This Keyword
•this is a reference variable in Java that refers to the current object of the class.
•It is commonly used to resolve naming conflicts and perform object-based operations within class
methods or constructors.
[Link] = age;
void display() {
[Link]();
}
This keyword
Student() { Unknown -0
this("Unknown", 0); // Calls parameterized constructor
}
void display() {
[Link](name + " - " + age);
}
void display() {
[Link]("Name: " + name);
}
Output
Name: John
Garbage Collection
Garbage Collection (GC) in Java is the process by which the Java Virtual Machine (JVM)
automatically removes unused (unreferenced) objects from memory.
This helps to free up memory and avoid memory leaks.
Java handles memory management automatically, so you don’t need to manually delete objects.
How It Works:
🔸 When no references to an object exist, that object is assumed to be no longer needed, and the
memory it occupies can be reclaimed by the JVM.
🔸 There is no need to explicitly destroy objects. Java handles this automatically.
🔸 Garbage collection occurs sporadically, not immediately after an object becomes unused.
🔸 GC does not occur just because an object becomes unreferenced. It's triggered by the JVM
based on memory needs and system behavior.
Garbage Collection
Finalize() Method
1. Write the general form of a class in Java. Explain class definition and member access with suitable program.
2. Explain two step procedure to create objects (class instance) with suitable program.
3. Explain assignment of objects with suitable example.
4. Explain general form of method definition in Java. Explain method definitions with suitable programs for:
a. Methods with no parameters and no return value
b. Methods with no parameters and return value
c. Methods with parameters and return value
5. Explain the role of constructors with an example. Explain with a program
(a) default constructor
(b) parameterized constructor
6. Explain the role of ‘this’ in parameter and instance variable name collision handling with suitable programming example.
7. Develop a Java program to define a class ‘2DBox’ with data members ‘length and width’. Define a class member method to calculate the area
of 2DBox and print box dimensions. Develop main method to illustrate the creation of objects, member access and use of methods suitably.
8. Develop a Java program to define a class ‘Customer’ with data members like Name, Employment and Age. Define a constructor and methods
to change employment and age. Develop main method to illustrate object creation, member access and invocation of methods suitably.
MODULE-2
CHAPTER-2
"Imagine you're creating an add() method—sometimes you want to add two integers, other times two doubles, or maybe
three numbers. Instead of naming them addInt, addDouble, or addThreeNumbers, you can just overload add() with
different parameters. This makes the API easier to understand and maintain."
Rules for Method Overloading
Must have the same method name.
Parameter list must be different in:
Number of parameters
Type of parameters
Order of parameters
Return type alone cannot distinguish methods.
"For method overloading to work, the compiler must be able to distinguish the
methods based on the parameter list. The return type isn’t considered when
overloading, so changing only the return type will result in a compilation error."
public class MathOpsDemo {
Example of Overloading public static void main(String[] args) {
MathOps math = new MathOps();
// Calling add method with two integers
// File: [Link]
int result1 = [Link](10, 20);
class MathOps {
[Link]("Sum of 10 and 20 (int): " + result1);
// Method to add two integers
// Calling add method with two doubles
int add(int a, int b) {
double result2 = [Link](5.5, 6.5);
return a + b;
[Link]("Sum of 5.5 and 6.5 (double): " +
}
result2);
// Method to add two double values
// Calling add method with three integers
double add(double a, double b) { int result3 = [Link](1, 2, 3);
return a + b; [Link]("Sum of 1, 2 and 3 (int): " + result3);
} }
// Method to add three integers }
int add(int a, int b, int c) { Expected Output:
return a + b + c; Sum of 10 and 20 (int): 30
} Sum of 5.5 and 6.5 (double): 12.0
} Sum of 1, 2 and 3 (int): 6
How it Works?
Argument passing refers to how data is sent from one part of a program (usually the main() method) to a method when it's
called.
In Java, this happens when you call a method and pass values (arguments) to it. These values are received by parameters
in the method.
Note:
You can change object fields, but not the reference itself.
Primitives – Pass-by-Value Example
public class PrimitiveExample {
Java Support for Recursion: Recursion is the attribute that allows a method to
call itself. A method that calls itself is said to be recursive.
🔹 When a method calls itself, new local variables and parameters are allocated
storage on the stack, and the method code is executed with these new variables
from the start.
🔹 As each recursive call returns, the old local variables and parameters are
removed from the stack, and execution resumes at the point of the call inside the
method.
🔸 Limitation: Recursive versions may execute a bit slowly than the iterative
equivalent because of the overhead of the additional method calls.
🔸 Advantage: Clear and simpler version of iterative algorithms.
When to use recursion?
The problem can be divided into similar sub-problems
The depth is manageable (not too many recursive calls)
Code clarity is more important than performance
Static Methods:
Methods declared as static have several restrictions:
[Link] can only directly call other static methods of their class.
[Link] can only directly access static variables of their class.
[Link] cannot refer to this or super in any way.
Static Block:
If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded.
Note:
Static methods and variables can be used independently of any object outside the
defining class.
ToGeneral
do so, you need only specify the name of the class followed by the dot operator.
form:
[Link]();
Example:
// Demonstrate static variables, methods, Output
and blocks.
class UseStatic {
Static block initialized.
static int a = 3;
static int b;
// Static data
x = 42
static void meth(int x) { // Static method a=3
[Link]("x = " + x);
[Link]("a = " + a); b = 12
[Link]("b = " + b);
}
static { // Static block
[Link]("Static block
initialized.");
b = a * 4;
Explanation:
}
public static void main(String[] args) {
meth(42);
}
Key Concepts from the Example:
•Static variables like a and b are shared across all uses of the class.
}
•Static methods like meth() can be called without creating an object.
•The static block runs once, initializing static data before any method runs.
A static variable can be accessed using the class name and the dot operator —
This is how Java gives us a controlled version of global variables and methods.
Example:
class StaticDemo { Output:
static int a = 42; // Static a = 42
data b = 99
static int b = 99;
static void callme() { // Static
method
[Link]("a = " + a); What this does:
[Link] class has:
} •Two static variables: a = 42, b = 99
} •One static method: callme(), which
class StaticByName { prints the value of a
public static void main(String[] args) { [Link] class has:
•main() method that:
[Link](); •Calls [Link]() →
// Call static method prints a = 42
[Link]("b = " + •Accesses StaticDemo.b directly
→ prints b = 99
StaticDemo.b); // Access static variable
}
}
Final Keyword
•Java provides several modifiers to control access and behavior.
•The final keyword is used to prevent modification.
•It can be applied to:
1. Final Variables
Variables •A variable marked final cannot be Must bereassigned after
Methods initialization.
Classes •It becomes a constant.
• initialized:
• At declaration, or
• In a constructor (if it's an instance variable)
Example:
2. A method declared as final cannot be overridden by final int MAX = 100;
subclasses.
•Used to preserve implementation in inheritance.
Example: 3. Classes
class Parent {
•A final class cannot be extended.
final void show() { •Prevents inheritance completely.
[Link]("Can't be overridden");
} •Example:
} final class Vehicle {
// Cannot have subclasses
}
Example: Using final with Variable, Method, and Class
•In java, it is possible to define a class within another class; such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its enclosing
class.
•A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members of
the nested class.
•It is also possible to declare a nested class that is local to a block.
•There are two types of nested classes:
[Link] nested class
[Link]-static nested class / inner class
1. Static Nested Class:
A static nested class is one that has the static modifier applied.
Because it is static, it must access the non-static members of its enclosing class
through an object.
That is, it cannot refer to non-static members of its enclosing class directly.
2. Inner Class:
An inner class is a non-static nested class.
It has access to all of the variables and methods of its outer class and may refer to them
directly, just like other non-static members.
Members of the inner class are known only within the scope of the inner class and may not
be used by the outer class.
Example program demonstrating both static nested class and inner class:
1. Explain Java support for compile-time polymorphism by taking suitable programming example.
2. With a program, explain the effect of automatic type conversion in method overloading.
3. Explain constructor overloading with suitable class definition and program.
4. Explain with suitable program:
a) Objects as method parameters
b) Objects as constructor parameters
5. Explain passing of primitive types and passing of objects as arguments to methods with suitable programs.
6. Explain returning of objects from methods with a program.
7. Explain how recursion is implemented in Java?
What are the benefits of recursion in programming?
8. Explain with a program, Java support for encapsulation through visibility modifiers.
9. Explain the different roles of keyword static with programs.
10. Explain different roles of keyword final with programs.
11. Explain the role of static nested classes and inner classes with programs.
12. Develop a recursive version of generating, storing, and displaying the Fibonacci series