Methods and Objects
Adding a Method to a Class
• Java Methods are blocks of code that perform a
specific task. A method allows us to reuse code,
improving both efficiency and organization. All
methods in Java must belong to a class. Methods are
similar to functions and expose the behavior of
objects.
Program to demonstrate how to create and use a
method.
• public class ABC
• {
• public void printMessage() {
• System.out.println("Hello, Students!");
• }
• public static void main(String[] args) {
• // Create an instance of the Method class
• ABC obj = new ABC();
•
• // Calling the method
• obj.printMessage();
• }
• }
Syntax of a Method
Why Do We Break Code into Methods?
• Breaking code into separate methods helps improve
readability, reusability, and maintainability
• Reusability: Write once, use multiple times without
repeating code so that code reusability increase.
• Readability: Smaller, named methods make the code
easier to read and understand.
• Maintainability: It’s easier to fix bugs or update code
when it's organized into methods.
• Testing: Methods can be tested independently,
improving code reliability and easier debugging.
Types of Methods in Java
1. Predefined Method
• Predefined methods are the method that is already
defined in the Java class libraries. It is also known as
the standard library method or built-in method. For
example, random() method which is present in the
Math class and we can call it using
the ClassName.methodName() as shown in the
below example.
• Example :
• Math.random() // returns random value
• Math.PI // return pi value
2. User-defined Method
• The method written by the user or programmer is
known as a user-defined method. These methods are
modified according to the requirement.
• Example :
• Greet()
• setName()
Different Ways to Create Java Method
• There are two ways to create a method in Java:
• 1. Instance Method: Access the instance data using the
object name. Declared inside a class.
• Example :
• void method_name() {
• // instance method body
• }
• 2. Static Method: Access the static data using class name.
Declared inside class with static keyword.
• Example :
• static void method_name() {
• // static method body
• }
Method Signature
• It consists of the method name and a parameter list.
• Number of parameters
• Type of the parameters
• Order of the parameters
• Note: The return type and exceptions are not
considered as part of it.
• Method Signature of the above function:
• max(int x, int y) Number of parameters is 2, Type of
parameter is int.
Returning a Value
• return keyword in Java is a reserved keyword which
is used to exit from a method, with or without a
value. The usage of the return keyword can be
categorized into two cases:
• Methods returning a value
• Methods not returning a value
• 1. Methods Returning a Value
• For the methods that define a return type, the return
statement must be immediately followed by a return
value.
Example :
• class Calculator{
•
• // Method to calculate average
• double avg(double x, double y) {
• double res = (x + y) / 2.0;
• return res; // Return the calculated result
• }
• // Main driver method
• public static void main(String[] args) {
• System.out.println(new Calculator().avg(5.5, 6.5));
• }
• }
• 2. Methods Not Returning a Value
• For methods that do not return a value, the return
statement can be skipped. This case can be further
divided into two scenarios:
i. Method Without return in a void Function
class Geeks { // Method to calculate a reduced sum
void calc(int a, int b)
{ int res = (a + b) / 10;
System.out.println(res); }
// Main driver method public static void
main(String[] args) { new Geeks().calc(5, 5);
System.out.println("No return keyword is used, and
program executed successfully");
}}
ii. Methods With void Return Type
• class Geeks {
•
• // Method to check a condition
• void check(double v) {
• if (v < 9) {
• return; // Exit method if condition is met
• }
• v++;
• }
• // Main driver method
• public static void main(String[] args) {
• Geeks o = new Geeks();
• o.check(5.5);
• System.out.println("Program executed successfully");
• }
• }
Adding a Method That Takes Parameters
• To add a method that takes parameters in Java, you
define the parameters within the parentheses
following the method name in the method
declaration.
• Steps to add a method with parameters:
1. Define the method signature:
i. Specify the access modifier (e.g., public, private).
ii. Specify the static keyword if it's a static method
(belonging to the class, not an object).
iii. Specify the return type (e.g., void if it doesn't
return a value, int, String, etc.).
iv. Provide the method name.
v. Inside parentheses (), list the parameters, each with
its data type and a name, separated by commas if
there are multiple parameters.
Example :
public class MyClass {
public void greetUser(String name) { // 'name' is a
parameter of type String
System.out.println("Hello, " + name + "!");
}
public int addNumbers(int num1, int num2) { //
'num1' and 'num2' are parameters of type int
return num1 + num2;
}
}
• 2. Implement the method logic:
• Inside the method body (the code block enclosed
in {}), use the parameter variables as needed to
perform operations or calculations.
3. Call the method and pass arguments:
• When calling the method, provide actual values
(arguments) that match the data types and order of
the parameters defined in the method signature.
• Example :
• public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.greetUser("Alice"); // "Alice" is the argument
passed to the 'name' parameter
int sum = obj.addNumbers(10, 5); // 10 and 5 are
arguments passed to 'num1' and 'num2'
System.out.println("Sum: " + sum);
}
}
Key Points
• Parameters vs. Arguments:
• Parameters are the variables defined in the method
signature, while arguments are the actual values
passed when the method is called.
• Order and Type Matching:
• The order and data type of the arguments passed
during a method call must match the order and data
type of the parameters declared in the method.
• Scope:
• Parameters are local variables within the method
and can only be accessed inside that method.
The this Keyword
• In Java, "this" is a reference variable that refers to
the current object, or can be said "this" in Java is a
keyword that refers to the current object instance. It
is mainly used to,
• Call current class methods and fields
• To pass an instance of the current class as a
parameter
• To differentiate between the local and instance
variables.
• Using "this" reference can improve code readability
and reduce naming conflicts.
• The this keyword can be used to access instance variables
and methods of the object on which the method or
constructor is being invoked.
• Below is the implementation of "this" reference:
• public class Person {
• // Fields Declared
• String name;
• int age;
• // Constructor
• Person(String name, int age)
• {
• this.name = name;
• this.age = age;
• }
• // Getter for name
• public String get_name() { return name; }
• // Setter for name
• public void change_name(String name)
• {
• this.name = name;
• }
• // Method to Print the Details of
• // the person
• public void printDetails()
• {
• System.out.println("Name: " + this.name);
• System.out.println("Age: " + this.age);
• System.out.println();
• }
• // main function
• public static void main(String[] args)
• {
• // Objects Declared
• Person first = new Person("ABC", 18);
• Person second = new Person("XYZ", 22);
• first.printDetails();
• second.printDetails();
• first.change_name("PQR");
• System.out.println("Name has been changed to: "
• + first.get_name());
• }
• }
• Following are the ways to use the "this" keyword in
Java mentioned below:
• Using "this" keyword to refer to current class
instance variables.
• Using this() to invoke the current class constructor
• Using 'this' keyword to return the current class
instance
• Using 'this' keyword as the method parameter
• Using 'this' keyword to invoke the current class
method
• Using 'this' keyword as an argument in the
constructor call
• entioned below:
Method Overloading
• Method overloading in Java is a feature of
polymorphism that allows a class to have multiple
methods with the same name, provided their
parameter lists are different. This means that
methods can share a name as long as the number,
type, or order of their parameters differ.
• Key characteristics of Method Overloading:
• Same Method Name:
• All overloaded methods within a class must have the
identical name.
• Different Parameter Lists:
• The defining characteristic of method overloading is
the variation in the parameter list. This can be
achieved by:
• Different Number of Parameters: For
example, add(int a, int b) and add(int a, int b, int c).
• Different Data Types of Parameters: For
example, display(int a) and display(String a).
• Different Order of Parameters: For
example, calculateArea(double length, double
width) and calculateArea(double width, double
length) (though this is less common for distinct
functionality).
• Return Type:
• Overloaded methods can have the same or different
return types. The return type alone is not sufficient
to differentiate overloaded methods; the parameter
list must still vary.
• Access Modifiers:
• Overloaded methods can have different access
modifiers (e.g., public, private, protected).
• Example :
• public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
• // Method to add three integers (overloaded)
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles (overloaded)
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Calls the int
add(int, int) method
System.out.println(calc.add(5, 10, 15)); // Calls the int
add(int, int, int) method
System.out.println(calc.add(5.5, 10.2)); // Calls the
double add(double, double) method
}
}
Benefits of Method Overloading:
• Improved Readability:
• Allows for a more intuitive API where a single
method name can represent a common operation,
even when applied to different data types or with
varying numbers of arguments.
• Code Reusability:
• Reduces the need for multiple distinct method
names for similar functionalities.
• Flexibility:
• Provides options for calling methods with different
argument combinations without needing to
remember numerous unique method names.
• Method overloading is resolved at compile-time,
meaning the compiler determines which specific
overloaded method to invoke based on the
arguments provided in the method call. This is why it
is considered a form of compile-time polymorphism.
Object Creation
• In Java, object creation involves instantiating a class to
create an object, which is an instance of that class. The
most common and fundamental way to create an
object in Java is by using the new keyword.
• Using the new keyword:
• This is the primary method for object
creation. The new keyword allocates memory for the
new object on the heap and then calls the class's
constructor to initialize the object's state.
• Example :
• ClassName objectName = new ClassName(arguments);
• Student s1=new Student(10,20);
• Explanation :
• ClassName:
• Represents the name of the class you want to instantiate.
• objectName:
• Is the name of the reference variable that will hold the
reference to the newly created object.
• new:
• The operator that allocates memory and initiates the
object creation process.
• ClassName(arguments):
• This is a call to the class's constructor. Constructors are
special methods used to initialize the state of a new
object. They have the same name as the class and can
take arguments to set initial values for the object's
fields. If no explicit constructor is defined, Java provides a
default no-argument constructor.
• Example :
• class Dog {
String name;
int age;
// Constructor
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void bark() {
System.out.println(name + " says Woof!");
}
}
• public class ObjectCreationDemo {
public static void main(String[] args) {
// Creating a Dog object using the new keyword
Dog myDog = new Dog("Buddy", 3);
// Accessing object's state and behavior
System.out.println("My dog's name is: " +
myDog.name);
myDog.bark();
}
}
Using Object as a Parameter
• In Java, objects can be passed as parameters to
methods, similar to how primitive data types are
passed. When an object is passed as a parameter, a
reference to that object is passed, not a copy of the
object itself. This means that any modifications made
to the object within the method will affect the
original object outside the method.
How to use an Object as a Parameter:
• Define a Method with an Object Parameter:
• Specify the class name of the object as the data type
for the parameter in the method signature.
• Example :
• public class MyClass {
int value;
public MyClass(int value) {
this.value = value;
}
• // Method that takes an object of MyClass as a
parameter
public void modifyObject(MyClass obj) {
obj.value = obj.value * 2; // Modifies the passed object
}
// Another method for demonstration
public void compareObjects(MyClass otherObj) {
if (this.value == otherObj.value) {
System.out.println("Objects have the same value.");
} else {
System.out.println("Objects have different values.");
}
}
}
• Call the Method and Pass an Object:
• Create an instance of the object and pass it as an
argument when calling the method.
• public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(5);
System.out.println("Original value of obj1: " +
obj1.value); // Output: 10
• // Call modifyObject, passing obj1 as an argument
obj1.modifyObject(obj1);
System.out.println("Modified value of obj1: " +
obj1.value);
• // Output: 20
// Call compareObjects
obj1.compareObjects(obj2);
• // Output: Objects have different values.
}
}
Key Points:
• Pass-by-Reference (of the reference):
• Java uses "pass-by-value" for all parameters, but for
objects, the value being passed is the reference (memory
address) to the object. This allows the method to access
and modify the original object.
• Accessing Members:
• Inside the method, you can access the instance variables
and methods of the passed object using the dot operator
(e.g., obj.value).
• this Keyword:
• When an instance method is called on an object,
the this keyword refers to the object on which the
method was invoked, allowing you to differentiate
between the calling object and the object passed as a
parameter.
Returning Objects
• In Java, methods can return objects, similar to how they
return primitive data types. When a method returns an
object, it returns a reference to that object, allowing the
calling method to interact with the returned object.
• Steps to return an object from a method:
• Define the method's return type: The method's return
type must be the class of the object you intend to return.
• Example :
• public class MyClass {
// ... fields and methods ...
public AnotherClass createAndReturnObject() {
// ... method body ...
}
}
• Create or obtain the object to return: Inside the
method, you can create a new object using
the new keyword, or you can obtain an existing
object that needs to be returned.
• Example :
• public class MyClass {
public AnotherClass createAndReturnObject() {
AnotherClass newObject = new
AnotherClass("data"); // Create a new object
return newObject; // Return the new object
}
}
• Use the return statement: The return statement is
used to send the object reference back to the caller.
• Example :
• public class MyClass {
public AnotherClass createAndReturnObject() {
AnotherClass newObject = new
AnotherClass("data");
return newObject; // The 'return' statement sends
the object reference
}
}
One Complete Example
• class Box {
double width;
double height;
double depth;
// Constructor
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
• // Method that returns a new Box object with doubled
dimensions
Box doubleSize() {
return new Box(width * 2, height * 2, depth * 2);
}
}
public class ReturnObjectDemo {
public static void main(String args[]) {
Box myBox = new Box(10, 20, 15);
Box largerBox;
largerBox = myBox.doubleSize(); // Call the method that
returns an object
System.out.println("Original box dimensions: " + myBox.width
+ " " + myBox.height + " " + myBox.depth);
System.out.println("Larger box dimensions: " +
largerBox.width + " " + largerBox.height + " " +
largerBox.depth);
}
}
• In above example, the doubleSize() method of
the Box class creates and returns a new Box object
with dimensions twice that of the calling
object. The main method then assigns the returned
object to largerBox.
Array of Objects
• In Java, an array of objects is a data structure that
stores multiple references to objects of a specific
class. It allows for the management and
manipulation of a collection of objects of the same
type within a single, indexed structure.
• Creating an Array of Objects:
• Declare the array: This involves specifying the class
type followed by square brackets [] and the array
name.
• Syntax :
• ClassName[] arrayName;
• Example :
• Student[] students;
• Instantiate the array: This allocates memory for the array
itself, but not for the individual objects it will hold.
• Syntax :
• arrayName = new ClassName[size];
• Example :
• students = new Student[5];
• Instantiate individual objects and assign them to array
elements: Each element of the array initially
holds null references. You must explicitly create new
objects and assign them to each index.
• Syntax : arrayName[index] = new ClassName();
• // Using a default constructor
// or
arrayName[index] = new ClassName(arguments);
• // Using a parameterized constructor
• For example, to create and assign Student objects:
• students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
// ... and so on for other elements
• Accessing and Manipulating Objects in the Array:
• Once the array is populated with objects, you can
access and manipulate individual objects using their
index, similar to how you would with primitive type
arrays.
• // Accessing an object and calling its method
students[0].displayDetails();
// Modifying an object's attribute
students[1].setAge(23);
• An array of objects stores references to objects, not
the objects themselves.
• Each element of the array must be individually
instantiated with a new object.
• Arrays of objects are particularly useful when dealing
with collections of similar data, allowing for efficient
iteration and management.