Classes, Methods, Objects,
and Object Instantiation
Classes
Java is an object-oriented programming (OOP) language, where the basic building blocks
are classes and objects.
Classes in Java
A class is a blueprint or template for creating objects. It defines the structure and behavior
(fields and methods) that the objects of the class will have.
Key Features of a Class
Fields (Variables): Represent the properties or state of the class.
Methods: Define the behavior or actions that objects of the class can perform.
Constructors: Special methods used to initialize objects.
Classes
Declaration:
Use the class keyword.
The class name should follow Java naming conventions (e.g., PascalCase).
Syntax of a Class
class ClassName
{
// Fields (State)
dataType fieldName;
// Methods (Behavior)
returnType methodName(parameters)
{
// Method body
}
}
Classes
Example
class Car
{
// Fields
String brand;
int speed;
// Methods
void displayDetails()
{
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
In this example, Car is a class with fields brand and speed, and a method displayDetails().
Classes
Encapsulation:
Classes group fields and methods into a single unit, following the principle of
encapsulation.
Modifiers:
Access Modifiers: public, private, protected, or default (package-private).
Non-Access Modifiers: final, abstract, static.
Inheritance:
A class can inherit from another class using the extends keyword.
Types of Fields:
Instance Fields: Belong to an instance of the class (object). Each object has its own copy
of instance fields.
Static Fields: Shared among all instances of the class and belong to the class itself.
Declared using the static keyword.
Classes
Initialization:
Instance Fields: Initialized in constructors or directly at declaration.
Static Fields: Initialized in a static block or at declaration.
class Test
{
int instanceField = 10; // Instance field initialized at declaration
static int staticField = 20; // Static field initialized at declaration
}
•Memory Allocation:
Instance Fields: Allocated in the heap memory for each object.
Static Fields: Allocated once in the class area, shared by all objects.
Encapsulation:
Fields should be private and accessed using methods (getters and setters) to
ensure data integrity and encapsulation.
Methods
Methods in Java
A method is a block of code designed to perform a specific task. It can take input parameters,
perform actions, and optionally return a value.
Types of Methods
Instance Methods: Operate on an object’s state and require an object to be called.
Static Methods: Belong to the class and can be called without creating an object.
Types of Parameters
Formal Parameters: Declared in the method definition and receive values when the
method is called.
Actual Parameters: The values or arguments passed to a method during a call.
Methods
Syntax of a Method
returnType methodName(dataType parameter1, dataType parameter2, ...)
{
// Method body
}
Methods
Example:
class Example
{
void greet(String name) // Formal parameter
{
System.out.println("Hello, " + name + "!");
}
}
public class Main
{
public static void main(String[] args)
{
Example example = new Example();
example.greet("Alice"); // Actual parameter
}
}
Output : Hello, Alice!
Methods
Types of Value Passing in Java
Java supports two primary ways of passing values to methods:
Pass by Value
Java uses pass-by-value for method arguments.
A copy of the value is passed to the method.
Modifications to the parameter inside the method do not affect the original value.
Methods
Example: Primitive Data Types
class Example {
void modifyValue(int num) {
num = num + 10; // Changes only the local copy
System.out.println("Inside method: " + num);
}
}
public class Main {
public static void main(String[] args) {
int value = 5;
Example example = new Example();
example.modifyValue(value);
System.out.println("Outside method: " + value); // Original value remains unchanged
}
}
Output:
Inside method: 15
Outside method: 5
Methods
Pass by Reference (Simulated via Object References)
While Java doesn’t support true pass-by-reference, it passes object references by value.
This means modifications to the object inside the method affect the original object since
both refer to the same memory location.
Methods
class Example {
void modifyObject(Person person) {
person.name = "Updated Name"; // Modifies the actual object
}
}
class Person {
String name;
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Original Name";
Example example = new Example();
example.modifyObject(person);
System.out.println("Name after modification: " + person.name);
}
}
Output: Name after modification: Updated Name
Methods
Calling Methods in Java
Instance Methods
Called using an object of the class.
Can access both instance and static members.
Example
class Calculator {
int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // Create object
int sum = calc.add(10, 20); // Call instance method
System.out.println("Sum: " + sum);
}
}
Output: Sum: 30
Methods
Static Methods
•Called using the class name, without needing an object.
•Cannot access instance variables or methods directly.
Example
class MathUtils {
static int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.multiply(5, 4); // Call static method
System.out.println("Result: " + result);
}
}
Output: Result: 20
Methods
Method Chaining
Methods can be chained by returning the current object (this).
Example
class Builder {
StringBuilder sb = new StringBuilder();
Builder append(String str) {
sb.append(str);
return this;
}
String build() {
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Builder builder = new Builder();
String result = builder.append("Hello ").append("World!").build();
System.out.println(result);
}
}
Output: Hello World!
Methods
Method Overloading
A class can have multiple methods with the same name but different parameter lists.
The method called is determined by the number and type of arguments passed.
class Display {
void show(int number) {
System.out.println("Number: " + number);
}
void show(String message) {
System.out.println("Message: " + message);
}
}
public class Main {
public static void main(String[] args) {
Display display = new Display();
display.show(42); // Calls method with int parameter
display.show("Hello Java"); // Calls method with String parameter
}
}
Number: 42
Message: Hello Java
Methods
Key Takeaways
1.Parameters:
Formal parameters are defined in the method declaration.
Actual parameters are passed during method invocation.
2.Passing Values:
Java uses pass-by-value for primitives.
Object references allow simulated pass-by-reference.
3.Calling Methods:
Instance methods require an object.
Static methods can be called directly using the class name.
Overloaded methods allow flexibility based on parameter types.
4.Best Practices:
Use clear and descriptive parameter names.
Prefer immutability for objects passed to methods to avoid unintended side effects.
Avoid excessive method overloading to reduce ambiguity.
Classes
Example:
class Student
{
// Instance fields
private String name;
private int rollNumber;
// Static field
static String schoolName = "ABC High School";
// Constructor to initialize instance fields
Student(String name, int rollNumber)
{
this.name = name;
this.rollNumber = rollNumber;
}
Classes
// Getter methods to access private fields
public String getName()
{
return name;
}
public int getRollNumber()
{
return rollNumber;
}
// Method to display student details
void displayDetails()
{
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("School: " + schoolName);
}
}
Classes
public class Main
{
public static void main(String[] args)
{
// Creating objects
Student student1 = new Student("Alice", 101);
Student student2 = new Student("Bob", 102);
// Displaying details
student1.displayDetails();
student2.displayDetails();
}
}
Classes
Output:
Name: Alice
Roll Number: 101
School: ABC High School
Name: Bob
Roll Number: 102
School: ABC High School
Objects
Objects in Java
An object is a runtime instance of a class. It represents a specific entity that has:
State: Defined by the fields (variables).
Behavior: Defined by the methods.
Identity: A unique memory address.
Creating an Object
Objects are created using the new keyword, which calls the class constructor.
Objects
class Dog {
// Fields
String name;
String breed;
// Method
void bark() {
System.out.println(name + " is barking!");
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of Dog class
Dog dog1 = new Dog();
dog1.name = "Buddy";
dog1.breed = "Golden Retriever";
System.out.println("Dog Name: " + dog1.name);// Accessing fields and methods
System.out.println("Dog Breed: " + dog1.breed);
dog1.bark(); // Output: Buddy is barking!
}
}
Objects
Object Instantiation
Object instantiation is the process of creating an object from a class. It involves:
Memory Allocation: Memory is allocated to the object.
Constructor Call: Initializes the object’s fields.
Steps for Object Instantiation
Declaration: Declare a reference variable.
Example: ClassName objectName;
Instantiation: Use the new keyword to create the object.
Example: objectName = new ClassName();
Initialization: The constructor initializes the object’s fields.
Objects
class Person {
String name; Output:
int age;
Person(String name, int age) { // Constructor Name: Alice
this.name = name; Age: 30
this.age = age; Name: Bob
} Age: 25
void displayInfo() { // Method
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 30); // Creating objects
Person person2 = new Person("Bob", 25); // Creating objects
person1.displayInfo(); // Calling methods on objects
person2.displayInfo(); // Calling methods on objects
}
}
Objects
Comprehensive Example: Combining All Concepts
Let’s combine classes, methods, objects, and instantiation in a single example:
class Student {
String name;
int rollNumber; // Fields
int marks; // Fields
// Constructor
Student(String name, int rollNumber, int marks) {
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
// Instance Method
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
Objects
// Static Method
static void welcomeMessage()
{
System.out.println("Welcome to the Student Portal!");
}
}
public class Main {
public static void main(String[] args) {
Student.welcomeMessage(); // Calling the static method
Student student1 = new Student("John", 101, 85); // Creating objects
Student student2 = new Student("Emma", 102, 90); // Creating objects
student1.displayDetails(); // Calling instance methods
student2.displayDetails(); // Calling instance methods
}
Objects
Output:
Welcome to the Student Portal!
Name: John
Roll Number: 101
Marks: 85
Name: Emma
Roll Number: 102
Marks: 90
Classes
Key Takeaways
Classes
Act as a blueprint to define fields and methods.
Methods
Define actions.
Can be static (class-level) or instance (object-level).
Objects
Represent instances of classes.
Encapsulate state and behavior.
Object Instantiation
Involves memory allocation and constructor execution.
Methods
Practice Questions:
Java_FUN_L0_1 Print square root
Java_FUN_L0_2.Find the power
Java_FUN_L0_3.Check Perfect, Abundant, Deficient
Java_FUN_L0_4.Generate Prime numbers
Java_FUN_L0_5.Check Adam number
Java_FUN_L0_6.Count the Number of Digits
Java_FUN_L0_7.Difference between the largest and smallest Digit
Java_FUN_L0_8.Number of Factors
Java_FUN_L0_9.Decimal to Binary
Java_FUN_L0_10.Find the largest character from the given characters
Methods
Practice Questions:
Java_FUN_L1_1. Arithmetic Operators
Java_FUN_L1_2.Alphabets counter
Java_FUN_L1_3.Armstrong Number Check
Java_FUN_L1_4.Difference between reverse number and number
Java_FUN_L1_5.Seggregate vowels and consonants
Java_FUN_L1_6.Multiply the value inside the variable
Java_FUN_L1_7.Two Addresses of a variable are given to swap the values in it
Java_FUN_L1_8.Array max of three repeat
Java_FUN_L1_9.Read data using the class
Java_FUN_L1_10.Read the Bio using the class
Methods
Practice Questions:
Java FUN L2 1 String Expand
Java FUN L2 2.Array rotator
Java FUN L2.3 AT by group reverser
Java FUN L2 4.arr union
Java FUN L2 5.arr intersection
Java FUN L2 6 array expand
Java FUN L2 7.count frequency
Java FUN L2 8 Maximum product
Java FUN L2 9.Vowel sort
Java.FUN.L2 10.Rotate difference
THANK YOU