Methods,Classes,Object Instantiation
Methods,Classes,Object Instantiation
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.
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
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
Pass by Value
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";
// 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
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
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