[go: up one dir, main page]

0% found this document useful (0 votes)
3 views24 pages

Copy of Session 11 - Methods - Part 1

This document covers methods in Java, including their definition, method overloading, and passing objects as parameters. It explains the syntax for defining methods, the benefits of method overloading, and provides real-world examples such as banking and shopping applications. Additionally, it discusses the advantages of passing objects as parameters, emphasizing code reusability and encapsulation.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views24 pages

Copy of Session 11 - Methods - Part 1

This document covers methods in Java, including their definition, method overloading, and passing objects as parameters. It explains the syntax for defining methods, the benefits of method overloading, and provides real-world examples such as banking and shopping applications. Additionally, it discusses the advantages of passing objects as parameters, emphasizing code reusability and encapsulation.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - II

Session 11 - Methods - Part 1

1. Introduction & Defining Methods

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:

public int add(int a, int b) {


return a + b;
}

In this example, add is a method that takes two integer parameters and returns their sum. The
method body contains the logic that defines what the method does. Methods may return a value
or void if they do not return anything.
-

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.

Syntax of Method Overloading


class ClassName {
// Method 1: Accepting one integer argument
public void methodName(int a) {
// Method body
}

// Method 2: Accepting two integer arguments


public void methodName(int a, int b) {
// Method body
}

// Method 3: Accepting one double argument


public void methodName(double a) {
// Method body
}
}

In the above example, the method methodName is overloaded with different parameter types
(int and double) and different numbers of arguments (one or two).

Rules for Method Overloading


1. Different Parameter Lists: Methods must differ in the number of parameters, types of
parameters, or both.
2. Return Type Does Not Matter: The return type alone does not distinguish overloaded
methods. Simply changing the return type will not work.
3. Same Method Name: All methods must have the same name.

Real-Time Example: Banking Application


Consider a banking application where you need to calculate interest based on different types of
accounts. One method might calculate interest based on a savings account, another for a fixed
deposit account, and another for a recurring deposit account.

class BankAccount {

// Method 1: Calculates interest for savings account


public double calculateInterest(double principal, double rate) {
return (principal * rate) / 100;
}

// Method 2: Calculates interest for fixed deposit with tenure


public double calculateInterest(double principal, double rate, int years) {
return (principal * rate * years) / 100;
}

// Method 3: Calculates interest for recurring deposit with monthly installments


public double calculateInterest(double principal, double rate, int years, double
monthlyInstallment) {
return ((principal + (monthlyInstallment * years * 12)) * rate * years) / 100;
}
}

public class Main {


public static void main(String[] args) {
BankAccount account = new BankAccount();

// Savings account interest


System.out.println("Savings Account Interest: " +
account.calculateInterest(10000, 5.5));

// Fixed deposit interest for 5 years


System.out.println("Fixed Deposit Interest: " +
account.calculateInterest(10000, 6.5, 5));

// Recurring deposit interest


System.out.println("Recurring Deposit Interest: " +
account.calculateInterest(10000, 6.0, 3, 2000));
}
}

Output:

Savings Account Interest: 550.0


Fixed Deposit Interest: 3250.0
Recurring Deposit Interest: 7560.0

Real-Time Example: Online Shopping Platform
An e-commerce application might have a method to calculate the total price of items in the cart.
However, the price calculation could depend on whether the user applies a discount or buys
items in bulk.

class ShoppingCart {
// Method 1: Calculate price without discount
public double calculateTotalPrice(double price, int quantity) {
return price * quantity;
}

// Method 2: Calculate price with discount


public double calculateTotalPrice(double price, int quantity, double discount) {
return (price * quantity) - discount;
}

// Method 3: Calculate price with bulk discount


public double calculateTotalPrice(double price, int quantity, double discount,
boolean isBulkPurchase) {
if (isBulkPurchase) {
return (price * quantity * 0.9) - discount; // 10% bulk discount
}
return (price * quantity) - discount;
}
}

public class Main {


public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();

// 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));

// Bulk purchase with discount


System.out.println("Bulk Purchase Price: " + cart.calculateTotalPrice(100, 20,
100, true));
}
}

Output:

Total Price: 500.0


Total Price with Discount: 450.0
Bulk Purchase Price: 1700.0
Advantages of Method Overloading:
1. Code Readability: Using the same method name for related functionality improves
clarity.
2. Flexibility: Allows different implementations of a method for different parameter types.
3. Reusability: Code can be reused efficiently by using overloaded methods.

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.

3. Implement a Java class with a method calculateArea that is overloaded to handle


different shapes: one method calculates the area of a rectangle, and another calculates
the area of a circle. The methods should accept parameters necessary for the area
calculation.

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?

A) Methods must have different return types


B) Methods must have different names
C) Methods must have different parameter lists
D) Methods must be declared in the same class

Answer: C) Methods must have different parameter lists

2. Which of the following statements about method overloading is true?

A) Method overloading is determined by the return type of the method.


B) Method overloading allows methods with the same name but different
parameter lists.
C) Method overloading requires methods to have different names and parameter
lists.
D) Method overloading can only be done in different classes.

Answer: B) Method overloading allows methods with the same name but different
parameter lists.

3. In which of the following cases is method overloading NOT possible?

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

Answer: A) Integer: 10, Double: 10.5, String: Java

5. What will happen if you try to overload a method based solely on its return type in
Java?

A) It will compile successfully.


B) It will result in a compilation error.
C) It will create a new method with a different name.
D) It will overwrite the existing method.

Answer: B) It will result in a compilation error.

6. Which of the following methods are overloaded in the provided class?

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

Class Objects as Parameters in Methods


In Java, methods can accept class objects as parameters, just like they accept primitive data
types (e.g., int, double) or reference types (e.g., arrays, strings). Passing objects as
parameters allows methods to interact with and modify the attributes of the object. This concept
is powerful as it enables complex interactions between classes and objects, contributing to
Java's object-oriented design.

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:

return_type methodName(ClassName objectName) {


// Method body
}

Here:

● return_type is the type of value the method will return.


● methodName is the name of the method.
● ClassName is the name of the class whose object is being passed as a parameter.
● objectName is the name of the parameter object used inside the method.

Example:
class Employee {
// Fields
String name;
int age;
// Constructor
Employee(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display Employee details


void displayInfo() {
System.out.println("Name: " + name + ", 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
}
}

public class Main {


public static void main(String[] args) {
// Creating an Employee object
Employee emp1 = new Employee("John Doe", 30);

// Creating a Company object


Company comp = new Company();

// Passing Employee object as a parameter to promoteEmployee method


comp.promoteEmployee(emp1, 35); // Promoting and updating the age
}
}

Output:

Employee John Doe has been promoted.


Name: John Doe, Age: 35

Explanation:
● In the above example, the Employee class has two fields: name and age. The Company
class contains a method promoteEmployee that accepts an Employee object as a
parameter and modifies its age attribute.
● The method promoteEmployee takes two parameters: an Employee object and an
integer for the new age. Inside this method, the age of the employee object is modified,
and the updated details are displayed.
● This is an example of passing an object by reference, meaning that the method operates
on the actual object rather than a copy.

Real-time Scenario Example:


Let's say you're building a Library Management System, and you want to create a method that
accepts a Book object as a parameter and updates the availability of the book when a user
borrows it.

class Book {
// Fields
String title;
boolean isAvailable;

// Constructor
Book(String title) {
this.title = title;
this.isAvailable = true; // Book is initially available
}

// Method to display book info


void displayStatus() {
String status = isAvailable ? "Available" : "Not Available";
System.out.println("Book: " + title + ", Status: " + status);
}
}

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.");
}
}
}

public class Main {


public static void main(String[] args) {
// Creating a Book object
Book book1 = new Book("Java Programming");
// Creating a Library object
Library library = new Library();

// Display book status


book1.displayStatus();

// Borrow the book


library.borrowBook(book1);

// Display book status after borrowing


book1.displayStatus();
}
}

Output:

Book: Java Programming, Status: Available


You have borrowed the book: Java Programming
Book: Java Programming, Status: Not Available

Explanation:
● The Book class represents a book with a title and availability status (isAvailable).
The Library class contains the borrowBook method, which accepts a Book object as
a parameter and modifies its isAvailable field.
● In the Main class, a Book object is created and passed to the borrowBook method in
the Library class. After borrowing the book, its availability is updated, demonstrating
how the method operates on the actual object.

Advantages of Passing Objects as Parameters:


1. Code Reusability: You can pass the same object to multiple methods, avoiding
redundancy and enabling reuse of the object’s data.
2. Modify Object Attributes: When an object is passed to a method, you can modify its
attributes, and those changes persist outside the method because objects are passed by
reference.
3. Encapsulation: You can maintain data encapsulation by interacting with objects through
methods and constructors, reducing direct access to class fields.
4. Simplifies Complex Systems: Passing objects as parameters is essential for creating
complex, real-world systems where multiple objects need to interact with one another.

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.

Key Points to Remember:


● When you pass an object as a parameter, the method receives a reference to the object,
not a copy.
● Any changes made to the object inside the method affect the original object outside the
method.
● You can use objects as method parameters to perform operations on the object’s fields
or to pass information between different parts of your program.

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

1. What is the purpose of passing an object as a parameter to a method in Java?

A) To allow the method to modify the object's state


B) To prevent the method from modifying the object's state
C) To copy the object into a new instance
D) To create a new object inside the method

Answer: A) To allow the method to modify the object's state

2. Which of the following is true about passing objects to methods in Java?

A) Java passes objects by value, meaning a copy of the object is made.


B) Java passes objects by reference, allowing the method to modify the original
object.
C) Java passes objects by reference, creating a new object for the method.
D) Java passes objects by value, meaning only the reference to the object is
copied.

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?

A) The changes are reflected in the original object.


B) The changes are not reflected in the original object.
C) A new object is created inside the method.
D) The method will cause a compile-time error.

Answer: A) The changes are reflected in the original object.

5. How can you ensure that an object passed to a method does not get modified?

A) Use the final keyword with the method parameter


B) Make a copy of the object inside the method
C) Use a return type with the method
D) Declare the method as static

Answer: B) Make a copy of the object inside the method

6. Which of the following is a valid way to pass an object as a parameter to a method


in Java?

A) void method(SomeClass obj) where SomeClass is the class of the


object
B) void method(SomeClass obj, SomeClass obj) where both
parameters are of the same class
C) void method(SomeClass obj, int value) where SomeClass and
int are different types
D) All of the above

Answer: D) All of the above

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..

Access Control Mechanisms


1. Access Modifiers: Access modifiers define the visibility of classes, methods, and fields.
They help control access from outside the class or package.

Types of Access Modifiers in Java


Java provides four types of access modifiers:

1. Default (Package-Private)
2. Private
3. Protected
4. Public

1. Default Access Modifier


When no access modifier is explicitly specified, the default access modifier is applied.
This means that the class, method, or variable is accessible only within the same
package. It’s like sharing something within a specific group of people.

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.

// Package: library


package library;

class LibraryBooks {
void displayBooks() {
System.out.println("List of books available in the library.");
}
}

// Package: otherLibrary
package otherLibrary;
import library.LibraryBooks;

public class AccessBooks {


public static void main(String[] args) {
LibraryBooks books = new LibraryBooks(); // Compile-time error
books.displayBooks(); // Error: Cannot access due to default access
modifier
}
}

2. Private Access Modifier


The private access modifier is the most restrictive. Members declared as private
are accessible only within the class they are defined in. Think of it as your personal
diary; only you can read and write in it.

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;

public BankAccount(double initialBalance) {


this.accountBalance = initialBalance;
}

private void calculateInterest() {


accountBalance += accountBalance * 0.05;
}

public void deposit(double amount) {


accountBalance += amount;
}

public void withdraw(double amount) {


if (accountBalance >= amount) {
accountBalance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}
}

In this example, accountBalance and calculateInterest() are private and can
only be accessed within the BankAccount class.

3. Protected Access Modifier


The protected access modifier allows access within the same package and by
subclasses in different packages. It’s like a family secret; only your family members
(subclasses) and people within your household (package) know about it.

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;

public class Vehicle {


protected void engineDetails() {
System.out.println("Engine details: 2000cc, V6");
}
}

package vehicleModels;

import vehicleCompany.Vehicle;

public class Car extends Vehicle {


public void showDetails() {
engineDetails(); // Accessible due to protected access
}
}

4. Public Access Modifier


The public access modifier has the widest scope. Public members are accessible from
anywhere in the application. It’s like a public park; everyone can enter and use it.

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;

public class Company {


public String name = "Tech Innovators";
public String contactNumber = "+1-800-555-1234";

public void displayContactDetails() {


System.out.println("Contact us at: " + contactNumber);
}
}

package clientApp;

import companyInfo.Company;

public class Client {


public static void main(String[] args) {
Company company = new Company();
System.out.println("Company Name: " + company.name);
company.displayContactDetails(); // Accessible everywhere
}
}

Key Points to Remember

● Default (Package-Private): Accessible only within the same package. No


keyword is needed.
● Private: Accessible only within the same class.
● Protected: Accessible within the same package and by subclasses in different
packages.
● Public: Accessible from anywhere in the program.

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.

2. Access Control in Packages:

● 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.

3. Access Control with Inheritance:

● Protected Members: Subclasses can access protected members of their superclass.


This allows for extending and modifying the behavior of parent classes.
● Usage: Facilitates inheritance while maintaining a level of access control.

4. Access Control with Encapsulation:

● 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 not compile and show a compilation error.

2. Consider the following code snippet:


class Animal {
private void makeSound() {
System.out.println("Animal Sound");
}
}

class Dog extends Animal {


public void bark() {
makeSound();
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
d.bark();
}
}

What will happen when the code is executed?

A) It will print "Animal Sound".


B) It will result in a compilation error due to trying to access a private method.
C) It will compile but throw a runtime exception.
D) It will print "Dog Sound".

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)

Answer: D) default (no modifier)

4. What is the output of the following code?


class Library {
protected void issueBook() {
System.out.println("Book issued.");
}
}

class SchoolLibrary extends Library {


public static void main(String[] args) {
SchoolLibrary lib = new SchoolLibrary();
lib.issueBook();
}
}

A) The code will not compile because issueBook() is protected.
B) The code will print "Book issued.".
C) The code will compile but throw an exception at runtime.
D) The code will not compile because issueBook() should be private.

Answer: B) The code will print "Book issued."

5. Consider the following code snippet:


class Person {
void displayInfo() {
System.out.println("Person Info");
}
}

public class Main {


public static void main(String[] args) {
Person p = new Person();
p.displayInfo();
}
}

If displayInfo() has no access modifier, where will this method be accessible?
A) Only within the Person class.
B) Within the same class and subclasses outside the package.
C) Within the same package only.
D) From any class in any package.

Answer: C) Within the same package only.

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.

Answer: B) The code will not compile due to access control.

References

Methods in Java - Methods in Java, #24 Methods in JavaMethods in Java


Method Overloading - #25 Method Overloading in Java
Objects as Parameters - 7.8 Object Passing in Java
End of Session - 11

You might also like