Copy of Session 11 - Methods - Part 1
Copy of Session 11 - Methods - Part 1
THROUGH JAVA
UNIT - II
Introduction to Methods
Methods in Java are blocks of code designed to perform specific tasks, and they help in
organizing and reusing code efficiently. A method is invoked by calling it within other
methods or from different parts of the program. Methods promote modularity, allowing
you to break down complex programs into simpler, manageable components. They can
accept input through parameters, perform operations, and return a result. Java has two
types of methods: predefined methods (like System.out.println()) and user-
defined methods.
Defining Methods
To define a method in Java, you specify its name, return type, parameters (if any), and
the code that will be executed. The syntax for defining a method is:
returnType methodName(parameters) {
// method body
}
Example:
2. Method Overloading
Overloaded Methods:
Introduction to Method Overloading
Method overloading is a feature in Java that allows a class to have more than one method with
the same name, as long as their parameter lists (the number, types, or order of parameters)
differ. This allows the same method name to perform different tasks based on how it is called.
Why Use Method Overloading?
Method overloading improves code readability and reusability. It allows methods with the same
purpose but different types or numbers of inputs to coexist. For example, a method that
calculates the area of shapes might take different parameters for circles, rectangles, or
triangles.
class BankAccount {
class ShoppingCart {
// Method 1: Calculate price without discount
public double calculateTotalPrice(double price, int quantity) {
return price * quantity;
}
// No discount
System.out.println("Total Price: " + cart.calculateTotalPrice(100, 5));
// With discount
System.out.println("Total Price with Discount: " +
cart.calculateTotalPrice(100, 5, 50));
Method overloading is a powerful feature in Java that allows developers to define multiple
methods with the same name but different parameter lists. It helps in organizing methods that
perform similar functions but require different inputs, improving code maintainability and
flexibility.
Do It Yourself
1. Write a Java program that demonstrates method overloading by creating a class with
three add methods that accept different types of parameters (e.g., integers, doubles, and
strings) and return their sum or concatenation.
2. Create a Java class with two overloaded methods named display—one that takes an
integer parameter and prints it, and another that takes a string parameter and prints it.
Write a main method to test both display methods.
4. Write a Java program with a class containing two overloaded methods named multiply.
One method should take two integer parameters, and the other should take two double
parameters. Both methods should return the product of the numbers.
5. Create a Java class with a method print that is overloaded to handle different data types:
one method should print an integer, another should print a double, and a third should
print a string. Write a main method to test each version of the print method.
Quiz
1. What is the main requirement for method overloading in Java?
Answer: B) Method overloading allows methods with the same name but different
parameter lists.
A) Two methods with the same name and different number of parameters
B) Two methods with the same name and different parameter types
C) Two methods with the same name and same parameter types but different
return types
D) Two methods with the same name and different order of parameters
Answer: C) Two methods with the same name and same parameter types but different
return types
4. Consider the following code snippet. What will be the output of the main method?
class Test {
void show(int a) {
System.out.println("Integer: " + a);
}
void show(double a) {
System.out.println("Double: " + a);
}
void show(String a) {
System.out.println("String: " + a);
}
public static void main(String[] args) {
Test obj = new Test();
obj.show(10);
obj.show(10.5);
obj.show("Java");
}
}
A) Integer: 10, Double: 10.5, String: Java
B) Integer: 10, Integer: 10.5, String: Java
C) Integer: 10, String: 10.5, String: Java
D) Compilation error
5. What will happen if you try to overload a method based solely on its return type in
Java?
class OverloadExample {
void process(int a) { }
void process(double a) { }
void process(int a, int b) { }
void process(double a, double b) { }
}
A) process(int a) and process(double a)
B) process(int a) and process(int a, int b)
C) process(int a) and process(double a, double b)
D) All methods are considered overloaded.
Answer: D) All methods are considered overloaded.
3. Objects as Parameters
Key Concepts:
1. Class Object: A class object is an instance of a class that contains data (fields) and
behavior (methods).
2. Method Parameter: In Java, a method can accept an object as a parameter. The
method can then manipulate the object's fields and call its methods.
Syntax:
The syntax for passing class objects as parameters to a method is the same as passing any
other data type:
Example:
class Employee {
// Fields
String name;
int age;
// Constructor
Employee(String name, int age) {
this.name = name;
this.age = age;
}
class Company {
// Method to modify the employee's age
void promoteEmployee(Employee emp, int newAge) {
emp.age = newAge; // Modifying the age of the employee object
System.out.println("Employee " + emp.name + " has been promoted.");
emp.displayInfo(); // Display updated info
}
}
class Book {
// Fields
String title;
boolean isAvailable;
// Constructor
Book(String title) {
this.title = title;
this.isAvailable = true; // Book is initially available
}
class Library {
// Method to update the availability of the book when borrowed
void borrowBook(Book book) {
if (book.isAvailable) {
book.isAvailable = false;
System.out.println("You have borrowed the book: " + book.title);
} else {
System.out.println("Sorry, the book " + book.title + " is currently
unavailable.");
}
}
}
Disadvantages:
1. Unintended Modifications: Since objects are passed by reference, modifying the
object inside the method directly affects the object, which can lead to unintended side
effects if not handled carefully.
2. Higher Memory Usage: When dealing with large objects or numerous objects, passing
them around methods can consume more memory compared to passing primitive data
types.
Passing class objects as parameters in methods is a common and useful practice in Java
programming. It allows methods to manipulate objects, update their state, and pass them
around in a controlled manner. This feature is fundamental to building scalable, object-oriented
applications that can model real-world entities and behaviors efficiently.
Do It Yourself
1. Create a class Flight with fields for flightNumber and departureTime. Write a
method delayFlight(Flight f, int delayInMinutes) that modifies the
departureTime by adding the delay. In the main method, create a Flight object and
use the delayFlight method to adjust its departure time.
2. Design a class Movie with fields for title and rating. Create a method
compareRating(Movie m1, Movie m2) that compares the ratings of two Movie
objects and prints the title of the movie with the higher rating. In the main method,
create two Movie objects and use the compareRating method to find the better-rated
movie.
3. Create a class InventoryItem with fields for itemName and quantity. Write a
method restockItem(InventoryItem item, int additionalQuantity) that
adds more quantity to the existing item. In the main method, create an
InventoryItem object and use the restockItem method to increase the quantity.
Quiz
Answer: D) Java passes objects by value, meaning only the reference to the object is
copied.
3. Consider the following code snippet. What will be the output of the main method?
class Test {
int value;
void updateValue(Test t) {
t.value = 10;
}
public static void main(String[] args) {
Test obj = new Test();
obj.value = 5;
obj.updateValue(obj);
System.out.println(obj.value);
}
}
A) 5
B) 10
C) Compilation error
D) Runtime error
Answer: B) 10
4. What happens if you pass an object to a method and modify its fields within the
method?
5. How can you ensure that an object passed to a method does not get modified?
4. Access Controls
Access Control
Access control in Java governs how classes, methods, and fields can be accessed from other
parts of a program. This is crucial for encapsulating the implementation details of a class and
protecting its internal state. Java provides mechanisms to control access through access
modifiers and the structure of packages and classes..
1. Default (Package-Private)
2. Private
3. Protected
4. Public
Example:
Imagine you are running a community library. You have a list of books (LibraryBooks)
that is only available to the staff of that specific library. People from other libraries
(packages) can't access this list.
class LibraryBooks {
void displayBooks() {
System.out.println("List of books available in the library.");
}
}
// Package: otherLibrary
package otherLibrary;
import library.LibraryBooks;
Example:
Consider a class that handles the financial records of a customer in a bank. The account
balance should be a private member because only specific operations (like depositing or
withdrawing) should modify it.
package banking;
class BankAccount {
private double accountBalance;
Example:
Consider a scenario where you have a vehicle manufacturing company. The company
has a class for Vehicle that has a protected method engineDetails(). Only specific
models (subclasses) can access this method.
package vehicleCompany;
import vehicleCompany.Vehicle;
Example:
Consider a class that holds public information, such as a company's contact details. This
information should be available to everyone, both within and outside the company.
package companyInfo;
import companyInfo.Company;
Best Practices
- Use private for variables that should not be accessed or modified directly from
outside the class.
- Use protected when you want to allow access to subclasses but still keep
control over the data.
- Use public only when it is necessary to expose members to all parts of your
application.
● Package-Level Access: Classes and members with default access are accessible only
within the same package. This is useful for grouping related classes and controlling their
visibility.
● Usage: Helps in designing modular and cohesive packages that encapsulate
functionality.
● Encapsulation: The practice of hiding the internal state of an object and requiring all
interactions to be performed through methods. Encapsulation is enforced using private
fields and public getter and setter methods.
● Usage: Protects the integrity of an object's state and ensures that it can only be modified
in controlled ways.
Do It Yourself
1. Create a class with a private method that performs a calculation. Add a public method
that calls this private method internally. In the main method, create an object of the class
and attempt to call both the public and private methods. Observe the results.
2. Design a base class in which a method has protected access. Create a subclass that
extends the base class and attempts to access the protected method. In the main
method, create an object of the subclass and call the protected method.
3. Write a class in which a method has default (package-private) access. Then, create
another class in the same package and attempt to call the method from the second
class. In the main method, create an object of the second class and invoke the method.
4. Implement a class with three methods, each having different access control (private,
protected, public). In a subclass, attempt to access the protected method and override it.
From the main method, try to access all three methods as allowed by their access
control levels.
Quiz
1. What will happen if you try to access a private method outside the class in which it is
defined?
A) It will compile successfully but throw a runtime exception.
B) It will not compile and show a compilation error.
C) The private method will be accessible from any class in the same package.
D) The private method will be accessible only from subclasses.
Answer: B) It will result in a compilation error due to trying to access a private method.
3. Which of the following access modifiers allows a method to be accessible from within
the same package but not from outside the package?
A) public
B) private
C) protected
D) default (no modifier)
6. What will be the result of trying to access a protected method from a class in a
different package that does not extend the class containing the protected method?
A) The method will be accessible.
B) The code will not compile due to access control.
C) The method will throw an exception at runtime.
D) The protected method will be accessible only if it is called using the class name.
References