Class and object
In Java, Class is the most important concept in Object-Oriented Programming (OOP).
A Class is a: Blueprint, Template, Logical Structure
which is used to create Objects.
It represents a group of objects having similar:
• Properties (Variables)
• Behaviour (Methods)
Class Definition
A Class is a user-defined data type that contains, Data Members (Variables),
Member Functions (Methods).It is used to define the state and behaviour of an object.
Or
A class is a user defined data type which binds data and function into a single unit
and objects are the instance of a class. A class is declared by use of the class keyword.
Syntax of Class:
class ClassName
{
// Data Members
// Member Functions
}
A class is the fundamental building block of Java programming. It helps in designing
real-world entities into programming structures and enables the implementation of object-
oriented concepts like encapsulation, inheritance, and polymorphism.
Data Members (Variables)
Data Members are variables that are used to store the data or state of an object.
They represent the properties of an object.
Examples:
• Student → roll number, name, marks
• Car → color, model, speed
Syntax:
int rollno;
String name;
float marks;
These variables are declared inside the class but outside the method..
Member Functions (Methods)
Member Functions define the behaviour or actions of an object.
They specify what an object can do.
Examples:
• Student → study(), attendExam()
• Car → start(), stop()
Syntax:
void display()
{
[Link]("Displaying Student Details");
}
Methods operate on the data members of the class.
YouTube Link : FSwithSRIKANTH
Example Program:
class Student
{
int rollno;
String name;
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
}
Characteristics of Class:
➢ Class is a logical entity
➢ It is a collection of objects
➢ It does not occupy memory when declared
➢ Memory is allocated only when object is created
➢ A class can contain variables and methods
➢ A class can create multiple objects
➢ It supports data abstraction and encapsulation
➢ It forms the basis for object-oriented programming
Importance of Class
• Helps in data hiding
• Supports code reusability
• Makes program modular
• Improves maintainability
• Supports abstraction and encapsulation
YouTube Link : FSwithSRIKANTH
Object in Java
In Java, an Object is both a physical as well as a logical entity, whereas a Class is
only a logical entity.
• A Class is just a blueprint or template.
• An Object is the actual implementation of that blueprint.
In simple words:
Class = Design
Object = Real-world Entity created using that design
Definition of Object
An Object in Java can be defined as:
• A real-world entity
• A runtime entity
• An instance of a class
• An entity that contains state and behaviour
Any entity that has:
✔ Properties (State)
✔ Actions (Behaviour)
is known as an Object.
Object as an Instance of a Class
An object is created from a class.
• A Class acts as a template.
• An Object is the result or instance of that class.
Example:
• Class → Car
• Objects → BMW, Audi, Swift
So, different cars are objects created from the same class Car.
Syntax for Creating an Object:
ClassName objectName = new ClassName();
Ex:
class Student
{
int rollno;
String name;
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
}
class Test
{
public static void main(String args[])
{
Student s1 = new Student();
[Link] = 101;
[Link] = "Ravi";
[Link]();
}
}
YouTube Link : FSwithSRIKANTH
OutPut:-
Roll No: 101
Name: Ravi
Explanation
• Student → Class Name
• s1 → Object Name
• new → Allocates memory for object
• [Link] → Access data member
• [Link]() → Calling method using object
Characteristics of an Object
Every object in Java has the following three main characteristics:
State
Behaviour
Identity
State:-
State represents the data or values associated with an object.
It is stored in the form of variables.
Example:
For a Student object:
• Name
• Roll Number
• Marks
Behaviour
Behaviour represents the functionality or actions performed by an object.
It is defined using methods.
Example:
For a Bank Account object:
• deposit()
• withdraw()
• checkBalance()
Identity
Each object has a unique identity.
• This identity is internally maintained by the JVM (Java Virtual Machine).
• It is generally implemented using a unique reference or memory address.
• The identity is not visible to the user but helps JVM to distinguish between
objects.
Even if two objects have the same state and behaviour, they are considered different due
to their unique identity.
Memory Allocation for Objects
• Objects are stored in Heap Memory.
• Memory is allocated dynamically using the new keyword.
• Each object occupies separate memory space.
YouTube Link : FSwithSRIKANTH
Creation of Object
An object is created using the following syntax:
ClassName objectName = new ClassName();
Here:
• ClassName → Name of the class
• objectName → Reference variable
• new → Keyword used to allocate memory
• ClassName() → Constructor call
Accessing Object Members
Object members such as variables and methods are accessed using:
[Link];
[Link]();
Advantages of Objects
• Represents real-world entities
• Supports object-oriented programming
• Enables data hiding
• Improves code reusability
• Allows dynamic memory allocation
• Makes program modular and flexible
Multiple Objects
In Java, we can create more than one object from a single class.
Each object created from a class is called an instance of that class.
Even though all objects belong to the same class, each object will have:
• ✔ Separate copy of instance variables (Data Members)
• ✔ Same copy of methods (Member Functions)
Need for Multiple Objects
Multiple objects are created when we want to represent:
Different real-world entities using the same class.
Example:
If Student is a class, then:
• Ram
• Ravi
• Sita
are different objects of the same class Student.
Each student will have:
• Different roll number
• Different name
But all will use the same methods like:
• display()
Syntax for Creating Multiple Objects:
ClassName object1 = new ClassName();
ClassName object2 = new ClassName();
ClassName object3 = new ClassName();
YouTube Link : FSwithSRIKANTH
Example Program:
class Student
{
int rollno;
String name;
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
}
class Test
{
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student();
[Link] = 101;
[Link] = "Ravi";
[Link] = 102;
[Link] = "Sita";
[Link]();
[Link]();
}
}
OutPut:
Roll No: 101
Name: Ravi
Roll No: 102
Name: Sita
Here,
✓ Two objects s1 and s2 are created from class Student.
✓ Both objects have separate memory allocation.
✓ s1 stores Ravi’s details.
✓ s2 stores Sita’s details.
✓ The same method display() is used by both objects.
Note:-
➢ One class can create multiple objects
➢ Each object has its own copy of instance variables
➢ Methods are shared by all objects
➢ Memory is allocated separately for each object
YouTube Link : FSwithSRIKANTH
Methods in Java
A Method in Java is a collection of statements that performs a specific task.
• A method is used to execute a particular operation.
• It may or may not return a value to the caller.
• Methods help in code reusability, meaning the same code can be used multiple
times without rewriting it.
Methods are essential building blocks in Java programming that help perform
specific tasks efficiently. They improve readability, maintainability, and reusability of code
by allowing developers to divide large programs into smaller manageable parts.
In Java, every method must be declared inside a class.
A Method is a block of code that:
✔ Performs a specific task
✔ Executes when it is called
✔ May or may not return a value
Why Do We Use Methods?
Methods are used because they:
• Save time
• Reduce code repetition
• Improve program readability
• Make the program modular
• Support code reusability
• Simplify debugging and maintenance
Syntax: method declaration
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may
contain zero parameters.
• method body − The method body defines what the method does with the
statements.
YouTube Link : FSwithSRIKANTH
Method Invocation in Java
➢ In Java, writing a method alone is not enough. To execute the statements inside a
method, it must be called.
➢ The process of executing a method by calling it is known as Method Invocation.
➢ A method will perform its task only when it is invoked (called).
What is Method Invocation?
Method Invocation is the process of:
✔ Calling a method
✔ Passing values (if required)
✔ Executing the method body
✔ Returning the result (if any)
Calling Method and Called Method
When one method invokes another method, two methods are involved:
Calling Method
• The method which calls another method is known as the Calling Method.
• It is responsible for transferring control to another method.
• It may pass values (arguments) to the called method.
Called Method
• The method which is invoked by another method is known as the Called Method.
• It performs the required operation.
• It may return a value back to the calling method.
Flow of Method Invocation
1. The Calling Method calls another method.
2. Control transfers to the Called Method.
3. The Called Method executes its statements.
4. If required, it returns a value.
5. Control returns back to the Calling Method.
Syntax for Calling a Method
Calling a Method without Parameters : methodName();
Calling a Method with Parameters: methodName(value1, value2);
Calling Method of Another Class using Object: [Link]();
Example Program:
class Demo
{
int add(int x, int y) // Called Method
{
return x + y;
}
public static void main(String args[]) // Calling Method
{
Demo obj = new Demo();
int result = [Link](10, 20); // Method Invocation
[Link]("Sum = " + result);
}
}
OutPut: Sum = 30
YouTube Link : FSwithSRIKANTH
Method Overloading in Java
Method Overloading is one of the important features of Object-Oriented Programming
(OOP) in Java.
It allows a class to have more than one method with the same name, but with
different:
• Number of parameters
• Type of parameters
• Order of parameters
This improves the readability and reusability of the program.
Method Overloading is the process of defining multiple methods in the same class
having the same method name but different parameter lists.
It is also known as:
Compile-Time Polymorphism
Static Polymorphism
Early Binding
Method Overloading allows defining multiple methods with the same name but
different parameters, helping in achieving compile-time polymorphism and improving the
clarity and reusability of Java programs.
Why Method Overloading?
Method overloading is used to:
• Perform similar operations using the same method name
• Increase readability of the program
• Reduce the number of method names
• Support code reusability
• Make the program easier to understand
Example:
Instead of writing:
• addInt()
• addFloat()
• addDouble()
Conditions for Method Overloading
Methods are said to be overloaded if:
✔ They have the same name
✔ They are in the same class
✔ Their parameter list must be different
The difference in parameter list can be:
Number of Parameters
Data Type of Parameters
Order of Parameters
Method Signature
Method Signature consists of:
• Method Name
• Number of Parameters
• Type of Parameters
• Order of Parameters
Return type is not considered in method overloading.
YouTube Link : FSwithSRIKANTH
Syntax of Method Overloading
class ClassName
{
returnType methodName(parameter1)
{
// code
}
returnType methodName(parameter1, parameter2)
{
// code
}
returnType methodName(parameter1, parameter2, parameter3)
{
// code
}
}
Example: Method Overloading by Changing Number of Parameters
class Addition
{
int add(int a, int b)
{
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
public static void main(String args[])
{
Addition obj = new Addition();
[Link]("Sum of 2 numbers: " + [Link](10, 20));
[Link]("Sum of 3 numbers: " + [Link](10, 20, 30));
}
}
OutPut:
Sum of 2 numbers: 30
Su
m of 3 numbers: 60
YouTube Link : FSwithSRIKANTH
Example: Method Overloading by Changing Data Type of Parameters
class Addition
{
int add(int a, int b)
{
return a + b;
}
double add(double a, double b)
{
return a + b;
}
public static void main(String args[])
{
Addition obj = new Addition();
[Link]("Integer Sum: " + [Link](10, 20));
[Link]("Double Sum: " + [Link](10.5, 20.5));
}
}
OutPut:
Integer Sum: 30
Double Sum: 31.0
Example Method Overloading by Changing Order of Parameters
class Display
{
void show(int a, double b)
{
[Link]("Integer and Double");
}
void show(double b, int a)
{
[Link]("Double and Integer");
}
public static void main(String args[])
{
Display obj = new Display();
[Link](10, 20.5);
[Link](15.5, 25);
}
}
OutPut:-
Integer and Double
Double and Integer
YouTube Link : FSwithSRIKANTH
Constructors in Java
A Constructor in Java is a special type of method that is used to:
✔ Initialize the instance variables of an object
✔ Allocate memory to the object
✔ Set the initial values to object data members
A constructor is automatically called when an object is created.
Definition
A Constructor is a special member function of a class whose:
• Name is the same as the class name
• It does not have any return type (not even void)
• It is automatically invoked at the time of object creation
Characteristics of Constructor
• Constructor name must be the same as class name
• It is called automatically when object is created
• It does not return any value
• It is used to initialize object data members
• It can be overloaded
• It is executed only once for each object
Advantages of Constructors
• Initializes object automatically
• Saves time for assigning values
• Helps in object creation
• Improves code readability
• Supports constructor overloading
Types of Constructors in Java
Java supports two types of constructors:
Default Constructor
Parameterized Constructor
Default Constructor:
A Default Constructor is a constructor that:
• Does not take any parameters
• Initializes the object with default values
• Is automatically created by the compiler if no constructor is defined in the class
Syntax of Default Constructor
class ClassName
{
ClassName()
{
// initialization code
}
}
YouTube Link : FSwithSRIKANTH
Example Program
class Student
{
int rollno;
String name;
Student() // Default Constructor
{
rollno = 101;
name = "Ravi";
}
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
public static void main(String args[])
{
Student s1 = new Student(); // Constructor is called
[Link]();
}
}
OutPut:
Roll No: 101
Name: Ravi
Parameterized Constructor:-
A Parameterized Constructor is a constructor that:
• Accepts parameters (arguments)
• Initializes the object with user-defined values
• Allows different objects to have different initial values
Syntax of Parameterized Constructor
class ClassName
{
ClassName(parameter1, parameter2)
{
// initialization code
}
}
Example Program
class Student
{
int rollno;
String name;
Student(int r, String n) // Parameterized Constructor
{
rollno = r;
YouTube Link : FSwithSRIKANTH
name = n;
}
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
public static void main(String args[])
{
Student s1 = new Student(101, "Ravi");
Student s2 = new Student(102, "Sita");
[Link]();
[Link]();
}
}
OutPut:-
Roll No: 101
Name: Ravi
Roll No: 102
Name: Sita
Difference Between Default and Parameterized Constructor
Default Constructor Parameterized Constructor
No parameters Takes parameters
Assigns default values Assigns user-defined values
Automatically created by compiler Must be defined by programmer
Initializes same values Initializes different values
Why Java Does Not Support Copy Constructor
➢ Java does not provide built-in support for copy constructors like C++.
➢ This is because Java uses reference variables to handle objects.
➢ When one object is assigned to another, both refer to the same memory location
instead of creating a new copy.
➢ Automatic copying of objects may lead to unnecessary memory usage and
performance issues.
➢ Java provides alternative mechanisms such as the clone() method for object
copying.
➢ If required, programmers can create a copy constructor manually in Java.
➢ This allows controlled copying of object data and avoids accidental modification of
original objects
YouTube Link : FSwithSRIKANTH
Constructor Overloading in Java
In Java, a class can have more than one constructor with the same name but different
parameter lists. This concept is known as Constructor Overloading
It allows a class to initialize objects in different ways using different sets of parameters.
Constructor Overloading is the process of defining multiple constructors in the same
class having:
• The same class name
• Different number of parameters
• Different types of parameters
• Different order of parameters
Constructor Overloading enables a class to have multiple constructors with different
parameter lists, allowing objects to be initialized in various ways based on user
requirements.
Need for Constructor Overloading
Constructor overloading is used to:
• Initialize objects with different values
• Provide multiple ways of object creation
• Improve flexibility in object initialization
• Enhance readability of the program
• Support compile-time polymorphism
Conditions for Constructor Overloading
Constructors are overloaded when:
✔ They have the same name as the class
✔ Their parameter list must be different
The difference can be in:
Number of parameters
Data type of parameters
Order of parameters
Syntax of Constructor Overloading
class ClassName
{
ClassName()
{
// default constructor
}
ClassName(parameter1)
{
// constructor with one parameter
}
ClassName(parameter1, parameter2)
{
// constructor with two parameters
}
}
YouTube Link : FSwithSRIKANTH
Advantages of Constructor Overloading
• Initializes objects in multiple ways
• Improves code readability
• Saves programming time
• Makes program flexible
• Supports compile-time polymorphism
Example : Constructor Overloading by Changing Number of Parameters
class Student
{
int rollno;
String name;
Student() // Default Constructor
{
rollno = 100;
name = "Unknown";
}
Student(int r, String n) // Parameterized Constructor
{
rollno = r;
name = n;
}
void display()
{
[Link]("Roll No: " + rollno);
[Link]("Name: " + name);
}
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student(101, "Ravi");
[Link]();
[Link]();
}
}
Output
Roll No: 100
Name: Unknown
Roll No: 101
Name: Ravi
YouTube Link : FSwithSRIKANTH
Example: Constructor Overloading by Changing Data Types
class Addition
{
int sum;
Addition(int a, int b)
{
sum = a + b;
}
Addition(double a, double b)
{
sum = (int)(a + b);
}
void display()
{
[Link]("Sum = " + sum);
}
public static void main(String args[])
{
Addition obj1 = new Addition(10, 20);
Addition obj2 = new Addition(10.5, 20.5);
[Link]();
[Link]();
}
}
Output
Sum = 30
Sum = 31
YouTube Link : FSwithSRIKANTH
Cleaning-Up Unused Objects in Java (Garbage Collection)
In Java, objects are created dynamically using the new keyword and stored in heap
memory. During the execution of a program, some objects may no longer be required by
the application, but they still remain in memory. These unused objects unnecessarily
occupy memory space and may affect the performance of the system. To manage such
situations, Java provides an automatic memory management mechanism known as
Garbage Collection.
Garbage Collection (GC) is the process of identifying and removing unused or
unreachable objects from memory so that the memory can be reused for future object
creation. This process is handled automatically by the Garbage Collector, which is a part
of the Java Virtual Machine (JVM). The programmer does not need to manually free the
memory of unused objects, as Java takes care of memory management automatically.
An object becomes eligible for Garbage Collection when it is no longer referenced by
any active part of the program. This may happen when the reference variable of an object
is assigned to null, when one reference variable is assigned to another object, or when an
object is created anonymously without any reference. In such cases, the object becomes
unreachable and is considered ready for removal from memory.
Although Garbage Collection is automatically performed by the JVM, the
programmer can request it by using methods such as [Link]() or
[Link]().gc(). However, this is only a request to the JVM and not a command.
The JVM may decide whether or not to perform Garbage Collection immediately based on
memory availability and system requirements.
Earlier, Java provided a method called finalize() which was invoked before an object
was destroyed by the Garbage Collector. This method was used to perform cleanup
operations. However, from Java 9 onwards, the finalize() method has been deprecated
because it is unreliable, unpredictable, and may lead to performance issues. The execution
of this method is not guaranteed, and therefore it is not recommended for use in modern
Java applications.
In modern Java programming, developers are encouraged to use better alternatives
such as try-with-resources and the AutoCloseable interface for resource management
instead of relying on the deprecated finalize() method. Thus, Garbage Collection plays an
important role in efficient memory management by automatically cleaning up unused
objects and improving overall application performance.
Syntax for Requesting Garbage Collection
Garbage Collection is automatically performed by JVM.
However, we can request JVM to perform Garbage Collection using the following syntax:
[Link]();
Or
[Link]().gc();
Note: It is only a request to JVM, not a command.
YouTube Link : FSwithSRIKANTH
Sample Example Program
class Demo
{
public static void main(String args[])
{
Demo obj1 = new Demo();
Demo obj2 = new Demo();
obj1 = null; // Object becomes eligible for GC
obj2 = null; // Object becomes eligible for GC
[Link](); // Requesting Garbage Collection
[Link]("Garbage Collection Requested");
}
}
OutPut:
Garbage Collection Requested
Explanation
• Two objects obj1 and obj2 are created.
• Their references are assigned to null.
• These objects become eligible for Garbage Collection.
• [Link]() requests JVM to clean up unused objects.
• The message is displayed after requesting Garbage Collection.
YouTube Link : FSwithSRIKANTH