0% found this document useful (0 votes)
7 views30 pages

Copy of Session 12 - Methods - Part 2

This document covers recursive methods in Java, explaining their definition, base conditions, and examples such as factorial and Fibonacci calculations. It discusses the advantages and disadvantages of recursion, memory allocation, and potential errors like stack overflow. Additionally, it introduces method nesting in Java, illustrating its use in organizing code through examples like a banking system.

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)
7 views30 pages

Copy of Session 12 - Methods - Part 2

This document covers recursive methods in Java, explaining their definition, base conditions, and examples such as factorial and Fibonacci calculations. It discusses the advantages and disadvantages of recursion, memory allocation, and potential errors like stack overflow. Additionally, it introduces method nesting in Java, illustrating its use in organizing code through examples like a banking system.

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/ 30

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - II

Session 12 - Methods - Part 2

1. Recursive Methods

Recursive Methods in Java


Definition:

In Java, recursion is a process in which a method calls itself directly or indirectly. The method
that performs this self-call is known as a recursive method. Recursive algorithms are powerful
tools for solving problems that can be divided into similar sub-problems. Examples of problems
solved using recursion include the Towers of Hanoi, tree traversals (Inorder, Preorder,
Postorder), and Depth-First Search (DFS) of graphs.

Base Condition in Recursion:

In a recursive program, the base case provides the solution for the simplest instance of the
problem and serves as a stopping point for the recursion. The solution to more complex
instances of the problem is expressed in terms of smaller, simpler sub-problems.

Example of Factorial Calculation:


The factorial of a number ( n ) (denoted as ( n! )) is the product of all positive integers less than
or equal to ( n ). The factorial of ( n ) can be computed recursively by defining the factorial of
( n ) in terms of the factorial of ( n-1 ).

int fact(int n) {
if (n <= 1) // base case
return 1;
else
return n * fact(n - 1); // recursive case
}

In this example, the base case is defined as ( n \leq 1 ), returning 1. For larger values of ( n ),
the method recursively calls itself with ( n-1 ) until the base case is reached.

Working of Recursion:

The essence of recursion is to solve a problem by breaking it down into smaller instances of the
same problem and combining the results. For instance, to compute the factorial of ( n ), if you
know the factorial of ( n-1 ), you can compute ( n! ) as ( n \times (n-1)! ). The base case for the
factorial problem is ( n = 0 ), where the factorial is defined as 1.

Java Recursion Programs:

1. Factorial Using Recursion

The factorial of a number ( N ) is calculated as the product of all positive integers from 1 to ( N ).
Below is a Java implementation of the factorial calculation using recursion:

// Java Program to implement Factorial using recursion


class GFG {

// Recursive method to calculate factorial


int fact(int n) {
int result;

if (n == 1) // Base case
return 1;
result = fact(n - 1) * n; // Recursive case
return result;
}
}

// Driver Class
class Recursion {

// Main function
public static void main(String[] args) {
GFG f = new GFG();

System.out.println("Factorial of 3 is " + f.fact(3));


System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

Output:

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

2. Fibonacci Series

Fibonacci Numbers are the integer sequence where Fib(N) = Fib(N-2) + Fib(N-1). Below is an
example to find 3,4,5.

● Fib(3) = Fib(2) + Fib(1) = Fib(1) + 0 + 1 = 1+1 = 2

● Fib(4) = Fib(3) + Fib(2) = 2+1 = 3

● Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5


// Java Program to implement Fibonacci Series
import java.io.*;

class GFG {

// Function to return Fibonacci value


static int Fib(int N) {
if (N == 0 || N == 1) // Base case
return N;
return Fib(N - 1) + Fib(N - 2); // Recursive case
}

// Main function
public static void main(String[] args) {
System.out.println("Fibonacci of " + 3 + " is " + Fib(3));
System.out.println("Fibonacci of " + 4 + " is " + Fib(4));
System.out.println("Fibonacci of " + 5 + " is " + Fib(5));
}
}

Output:

Fibonacci of 3 is 2
Fibonacci of 4 is 3
Fibonacci of 5 is 5

Stack Overflow Error:

If the base case is not defined properly, the recursion may continue indefinitely, causing a stack
overflow error. For example:

int fact(int n) {
// Incorrect base case (it may cause stack overflow).
if (n == 100)
return 1;
else
return n * fact(n - 1);
}

If fact(10) is called, it will call fact(9), fact(8), and so on, but will never reach 100. This
will eventually lead to a stack overflow error as the memory is exhausted.

Memory Allocation in Recursion:

When a function is called, memory is allocated on the stack for that function's local variables
and state. For recursive calls, each function call creates a new stack frame. Each call has its
own set of local variables. Once the base case is reached, the function returns its value, and the
stack frames are de-allocated, allowing the previous calls to complete.

Example of Recursion:

// A Java program to demonstrate working of recursion


class GFG {
static void printFun(int test) {
if (test < 1)
return;
else {
System.out.printf("%d ", test);
// Recursive call
printFun(test - 1);
System.out.printf("%d ", test);
return;
}
}

public static void main(String[] args) {


int test = 3;
printFun(test);
}
}

Output:

3 2 1 1 2 3

Explanation:

When printFun(3) is called, it prints 3, then calls printFun(2), which prints 2, and so forth.
After reaching the base case, the function starts returning, printing the numbers in reverse order
as it returns to the previous calls.

Advantages of Recursive Programming:

- Provides a clean and simple way to write code for problems that naturally fit a recursive
approach.
- Particularly useful for problems like tree traversals and the Tower of Hanoi, where the
recursive approach mirrors the problem structure.

Disadvantages of Recursive Programming:

- Higher space requirements due to maintaining multiple stack frames.


- Increased time complexity due to the overhead of function calls.
- Recursive programs may be less efficient than iterative solutions for certain problems.

Note: Both recursive and iterative solutions have the same problem-solving capabilities. Any
problem that can be solved recursively can also be solved iteratively, and vice versa.

Do It Yourself
1. Write a recursive method in Java that calculates the sum of all natural numbers up to
nnn. For example, if n=5n = 5n=5, the method should return 1+2+3+4+51 + 2 + 3 + 4 +
51+2+3+4+5. Call this method from the main method and print the result for n=5n =
5n=5.
2. Create a recursive method in Java to calculate xxx raised to the power of yyy (i.e.,
xyx^yxy). For example, if x=2x = 2x=2 and y=3y = 3y=3, the method should return 8.
Test this method with x=2x = 2x=2 and y=3y = 3y=3.
3. Create a recursive method gcd(int a, int b) that calculates the greatest common
divisor of two integers aaa and bbb. For example, gcd(48, 18) should return 6.

Quiz

Here are five multiple-choice questions (MCQs) on recursive methods in Java, along with their
answers:

1. What is a base case in recursion?

A) The condition that stops the recursion


B) The initial value of the recursive method
C) The method that calls itself
D) The number of recursive calls

Answer: A) The condition that stops the recursion

2. Which of the following is an example of a problem that can be solved using


recursion?

A) Sorting a list of numbers


B) Computing the factorial of a number
C) Finding the maximum value in an array
D) Both B and C

Answer: D) Both B and C

3. What happens if a recursive method does not have a base case?

A) The method will complete execution normally


B) The method will cause a compile-time error
C) The method will result in infinite recursion and a stack overflow error
D) The method will return zero
Answer: C) The method will result in infinite recursion and a stack overflow error

4. In the recursive method int factorial(int n) { if (n == 0) return 1;


else return n * factorial(n - 1); }, what will factorial(3) return?

A) 3
B) 6
C) 9
D) 12

Answer: B) 6

5. Which statement about recursion in Java is true?

A) Recursive methods always use more memory than iterative methods.


B) Recursion is always faster than iteration.
C) Recursive methods must always have a base case to avoid infinite recursion.
D) Recursive methods cannot return values.

Answer: C) Recursive methods must always have a base case to avoid infinite
recursion

2. Nesting of Methods

Nesting of Methods in Java


In Java, method nesting refers to the practice of calling one method from another method
within the same class. Nesting of methods can help break down complex tasks into smaller,
manageable operations while improving code modularity and readability.

Syntax
Java does not allow declaring a method within another method directly (as in some other
programming languages like Python). However, nesting of method calls is allowed, where one
method calls another, forming a hierarchy of method executions.

General Syntax:
class ClassName {
// Method 1
void method1() {
// Method body
}

// Method 2
void method2() {
// Method1 is called inside Method2
method1();
}
}

In this example, method2() calls method1() within its body. This kind of nesting helps in
organizing functionality and code reusability.

Example: Real-Time Scenario - Banking System


Consider a scenario in a banking system where a user performs multiple operations, such as
checking account balance, withdrawing funds, and calculating transaction charges. Nesting
methods can be used to simplify these tasks.

Example:
class BankAccount {
double balance;

// Method to check balance


double checkBalance() {
System.out.println("Checking balance...");
return balance;
}

// Method to deduct transaction charges


void deductCharges() {
System.out.println("Deducting transaction charges...");
balance -= 10; // Deduct a flat charge
}

// Method to withdraw amount


void withdraw(double amount) {
// Checking balance first (nested method call)
if (checkBalance() >= amount) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + " successful.");
// Deducting charges after withdrawal
deductCharges(); // Nested method call
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}

// Method to deposit amount


void deposit(double amount) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
}

// Main method to demonstrate nesting


public static void main(String[] args) {
BankAccount account = new BankAccount();
account.balance = 500; // Set initial balance
account.deposit(200); // Deposit funds
account.withdraw(100); // Withdraw funds
}
}

Output:
Deposit of $200 successful.
Checking balance...
Withdrawal of $100 successful.
Deducting transaction charges...

Explanation:
- In this example, withdraw() method calls both checkBalance() and
deductCharges() to check the account balance and deduct charges. These methods
are "nested" within the withdraw() method.
- This example simulates real-time banking operations where multiple steps need to be
performed together, making method nesting an effective way to organize related tasks.

Key Points
1. Improved Code Modularity: Nesting methods breaks down larger, complex tasks into
smaller, reusable methods. Each method performs a specific task, improving code
readability and reusability.

2. Maintainability: Smaller methods make maintaining and debugging code easier,


especially in real-time systems where multiple operations occur frequently.

3. Flexibility in Design: Using nested methods allows you to modify one method's
functionality without impacting others. For example, if the transaction charges change,
the deductCharges() method can be updated without altering the other methods.
4. Real-Time Usage: In real-world applications like banking, online shopping, or hotel
booking, method nesting is essential to manage sequences of operations in a clean and
organized manner.

Nesting methods in Java is a useful technique for organizing code and promoting reuse. While
Java does not allow the direct declaration of methods inside other methods, it supports method
nesting via calls, allowing one method to invoke others, making code simpler and more
maintainable in complex systems.

Do It Yourself
1. Implement a program that converts between Celsius, Fahrenheit, and Kelvin using
nested conversion methods.
2. Write a program that adds items to a cart, calculates the total, and applies discounts
using nested method calls.
3. Design a program where nested methods check book availability, issue books, and
calculate overdue fines.
4. Create a program that calculates the final grade using nested methods to compute
marks from assignments, exams, and projects.

Quiz

1. Which of the following is true about nested classes in Java?


A) Nested classes are allowed to access only static members of the outer class
B) Nested classes can access all members of the outer class, including private ones
C) Nested classes cannot be declared private or protected
D) Nested classes are not allowed in Java

Answer: B) Nested classes can access all members of the outer class, including private
ones

2. What is the correct syntax to create an object of an inner class?

class Outer {
class Inner {
void show() {
System.out.println("Inside Inner class");
}
}
}

class Test {
public static void main(String[] args) {
// Which of the following is the correct way to instantiate Inner class?
}
}

A) Inner i = new Inner();
B) Outer.Inner i = new Outer.Inner();
C) Outer.Inner i = new Outer().new Inner();
D) Outer.Inner i = new Inner();

Answer: C) Outer.Inner i = new Outer().new Inner();

3. Which type of nested class can access only static members of the outer class?
A) Static nested class
B) Non-static inner class
C) Anonymous inner class
D) Local inner class

Answer: A) Static nested class

4. Which of the following is a valid reason for using nested Java classes?
A) To reduce the visibility of a class
B) To create multiple objects of the outer class
C) To avoid memory leaks
D) To organize classes that are used only by the outer class

Answer: D) To organize classes that are used only by the outer class

5. Consider the following code:

class Outer {
private int x = 10;

class Inner {
void display() {
System.out.println(x);
}
}
}

public class Main {


public static void main(String[] args) {
Outer o = new Outer();
Outer.Inner i = o.new Inner();
i.display();
}
}

What will be the output?
A) Compilation error
B) Runtime error
C) 0
D) 10

Answer: D) 10

6. Which of the following statements is true about static nested classes?


A) Static nested classes can access non-static members of the outer class
B) Static nested classes are only accessible by the outer class
C) Static nested classes can be instantiated without an object of the outer class
D) Static nested classes cannot have constructors

Answer: C) Static nested classes can be instantiated without an object of the outer
class

4. Method Overriding

Method Overriding in Java


Method overriding is a key feature in Java that allows a subclass to provide a specific
implementation of a method that is already defined in its superclass. This capability is essential
for implementing Run Time Polymorphism, where the method that gets executed depends on
the type of object used to invoke it.

Basics of Method Overriding


Definition: Method overriding occurs when a subclass defines a method with the same name,
parameters, and return type as a method in its superclass. The method in the subclass
overrides the method in the superclass.
Key Points:

- Same Method Signature: The overriding method must have the same name, parameter
list, and return type (or subtype) as the method in the superclass.
- Access Modifiers: The access level of the overriding method can be the same or more
accessible than the method in the superclass (e.g., protected can be overridden as
public).
- Method Bodies: The implementation of the method in the subclass provides the specific
behavior.

Example of Method Overriding


// Base Class
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}

// Driver Class
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.makeSound(); // Output: Animal makes a sound

Animal myDog = new Dog();


myDog.makeSound(); // Output: Dog barks
}
}

Explanation:

- Animal is the superclass with a method makeSound().


- Dog is a subclass that overrides the makeSound() method.
- When the method is invoked using a reference of type Animal but pointing to a Dog
object, the overridden method in Dog is executed.

Rules for Java Method Overriding


1. Access Modifiers:

- An overriding method can have the same or more permissive access level
compared to the method in the superclass. For instance, if the superclass
method is protected, it can be overridden with protected or public, but not
with private.

class Parent {
protected void display() {
System.out.println("Display from Parent");
}
}

class Child extends Parent {


@Override
public void display() {
System.out.println("Display from Child");
}
}

2. Final Methods:

- Methods marked as final in the superclass cannot be overridden in


subclasses.

class Parent {
final void display() {
System.out.println("Final display from Parent");
}
}

class Child extends Parent {


// This would produce an error
// void display() { System.out.println("Display from Child"); }
}

3. Static Methods:
- Static methods cannot be overridden; they are subject to method hiding. The
method in the subclass hides the static method of the superclass.

class Parent {
static void display() {
System.out.println("Static display from Parent");
}
}

class Child extends Parent {


static void display() {
System.out.println("Static display from Child");
}
}

public class Main {


public static void main(String[] args) {
Parent.display(); // Output: Static display from Parent
Child.display(); // Output: Static display from Child
}
}

4. Private Methods:

- Private methods cannot be overridden as they are not accessible to subclasses.


They are only accessible within the class where they are declared.

class Parent {
private void display() {
System.out.println("Private display from Parent");
}
}

class Child extends Parent {


// This will not override the parent's private method
private void display() {
System.out.println("Private display from Child");
}
}

5. Covariant Return Types:

- From Java 5 onwards, the return type of the overriding method can be a subtype
of the return type declared in the superclass.
class Parent {
public Number getNumber() {
return 1;
}
}

class Child extends Parent {


@Override
public Integer getNumber() {
return 2;
}
}

6. Using super to Call Superclass Methods:

- The super keyword can be used to call methods from the superclass within the
overriding method.

class Parent {
void show() {
System.out.println("Parent's show()");
}
}

class Child extends Parent {


@Override
void show() {
super.show();
System.out.println("Child's show()");
}
}

public class Main {


public static void main(String[] args) {
Parent obj = new Child();
obj.show(); // Output: Parent's show() \n Child's show()
}
}

Do It Yourself
1. Create a base class Vehicle with a method start(). Create a subclass Car that
overrides start() to provide a specific implementation.

2. Define a base class Employee with a method calculateSalary(). Implement a


subclass Manager that overrides calculateSalary() to return a different salary
calculation.

3. Write a base class Shape with a method draw(). Create subclasses Circle and
Rectangle that override the draw() method to provide specific drawing behavior.

4. Implement a class Animal with a method eat(). Create a subclass Cat that overrides
the eat() method to provide a specific eating behavior.

5. Create a class Bird with a method fly(). Define a subclass Parrot that overrides
fly() to provide a detailed implementation of how a parrot flies.

Quiz

1. What is required for a method to override a method in Java?

- A) Same method name, different return type


- B) Same method name, same parameters
- C) Same method name, different parameters
- D) Different method name, same return type

Answer: B) Same method name, same parameters

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

- A) The overriding method can have a less restrictive access modifier.


- B) The overriding method must have the same return type as the method in the
superclass.
- C) Private methods can be overridden.
- D) Static methods are overridden, not hidden.
Answer: B) The overriding method must have the same return type as the method in the
superclass.

3. What will be the output of the following code?

class A {
void show() {
System.out.println("A");
}
}

class B extends A {
void show() {
System.out.println("B");
}
}

public class Main {


public static void main(String[] args) {
A obj = new B();
obj.show();
}
}

- A) A
- B) B
- C) Compilation Error
- D) Runtime Error

Answer: B) B

4. Can a final method be overridden in Java?

- A) Yes, it can be overridden


- B) No, it cannot be overridden
- C) It depends on the return type
- D) It depends on the access modifier

Answer: B) No, it cannot be overridden

5. If a superclass method throws a checked exception, what can be the exception


handling rule for the overridden method in the subclass?
- A) It can throw any checked exception.
- B) It can throw the same checked exception or its subclasses.
- C) It must throw the same checked exception.
- D) It must not throw any exception.

Answer: B) It can throw the same checked exception or its subclasses.

6. What will be the output of the following code?

class Parent {
static void display() {
System.out.println("Parent display");
}
}

class Child extends Parent {


static void display() {
System.out.println("Child display");
}
}

public class Main {


public static void main(String[] args) {
Parent.display();
Child.display();
}
}

- A) Parent display \n Child display
- B) Child display \n Child display
- C) Parent display \n Parent display
- D) Compilation Error

Answer: A) Parent display \n Child display


5. Method Overloading Vs Method
Overriding

Differences Between Method Overloading and Method Overriding:


Method Overloading and Method Overriding are both concepts related to polymorphism in
Java, but they function differently. Here's a detailed comparison between them:

Aspect Method Overloading Method Overriding

Polymorphism Type Compile-time polymorphism Run-time polymorphism

Purpose Increases readability by allowing Provides specific implementation


multiple methods with the same of a method already defined in
name but different parameters. the parent class.

Location Occurs within the same class. Involves two classes with an
inheritance relationship.

Inheritance Requirement Inheritance is not mandatory. Inheritance is mandatory.

Method Signature Methods must have the same Methods must have the same
name but different signatures name, signature, and return type.
(parameter lists).

Return Type The return type can be the same The return type must be the
or different. Parameters must same or co-variant.
change.

Binding Type Uses static binding (compile- Uses dynamic binding (run-time).
time).

Private/Final Methods Private and final methods can be Private and final methods cannot
overloaded. be overridden.

Argument List Must differ in method Must be the same in method


overloading. overriding.

Method Overloading
Method Overloading allows multiple methods in the same class to share the same name but
differ in their parameter lists. It's a type of compile-time polymorphism.

Example of Method Overloading:


class MethodOverloadingEx {
static int add(int a, int b) {
return a + b;
}

static int add(int a, int b, int c) {


return a + b + c;
}

public static void main(String args[]) {


System.out.println("add() with 2 parameters: " + add(4, 6));
System.out.println("add() with 3 parameters: " + add(4, 6, 7));
}
}

Output:

add() with 2 parameters: 10


add() with 3 parameters: 17

Method Overriding:

Method Overriding allows a subclass to provide a specific implementation of a method that is


already defined in its parent class. It is a type of runtime polymorphism.

Example of Method Overriding:


class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}

class Dog extends Animal {


@Override
void eat() {
System.out.println("Dog is eating.");
}

void eatAsAnimal() {
super.eat();
}
}

class MethodOverridingEx {
public static void main(String args[]) {
Dog dog = new Dog();
Animal animal = new Animal();

dog.eat(); // Calls Dog's eat method


animal.eat(); // Calls Animal's eat method

// Polymorphism
Animal animalDog = new Dog();
animalDog.eat(); // Calls Dog's eat method due to dynamic binding

// Calling base class method using subclass reference


((Dog) animalDog).eatAsAnimal();
}
}

Output:

Dog is eating.
Animal is eating.
Dog is eating.
Animal is eating.

Explanation:

● The eat() method is overridden in the Dog class, providing its own implementation
while the parent Animal class has its own.
● The base class method can be called using the super keyword within the subclass.

Key Takeaways:

● Method Overloading is primarily used to provide multiple ways to perform a similar


task, improving code readability.
● Method Overriding is used in inheritance hierarchies to modify or extend the behavior
of methods inherited from parent classes.
6. final and static in Methods

final and static in Methods in Java


In Java, the final and static keywords can be used with methods to modify their behavior.
These attributes serve distinct purposes in controlling method inheritance, overriding, and the
method's association with objects or classes.

1. Final Methods
When a method is declared final, subclasses cannot override it. This is typically used to prevent
modification of crucial functionality in derived classes.

Characteristics of final Methods:


- Prevent Overriding: A final method cannot be overridden by any subclass. This is
useful when a class wants to ensure that a specific method remains unchanged across
all subclasses.
- Inheritance: Although a subclass can inherit a final method, it cannot be modified in that
subclass.
- Performance Optimization: In some cases, marking methods as final allows the
compiler to optimize calls to those methods because it knows the implementation will not
change.

Example of a final Method:


class Vehicle {
final void start() {
System.out.println("Vehicle is starting.");
}
}

class Car extends Vehicle {


// This will cause a compile-time error
// void start() {
// System.out.println("Car is starting.");
// }
}

public class FinalMethodExample {


public static void main(String[] args) {
Car car = new Car();
car.start(); // Inherits the final method from Vehicle
}
}

Key Point: Trying to override the start() method in the Car class will result in a compile-
time error.

2. Static Methods
A static method in Java belongs to the class rather than to any specific instance (object) of
that class. This means static methods can be called without creating an object of the class.

Characteristics of static Methods:


- Class-Level Association: static methods are associated with the class itself, not with
any instance.
- Access without Object: They can be called using the class name directly.
- Cannot Use Instance Variables/Methods: static methods cannot directly access
instance variables or instance methods. They can only interact with static variables
and other static methods.
- Overriding Restriction: static methods cannot be overridden, but they can be hidden
by a subclass (this is known as method hiding).

Example of a static Method:


class Calculator {
static int add(int a, int b) {
return a + b;
}
}

public class StaticMethodExample {


public static void main(String[] args) {
// Calling static method without creating an object
int result = Calculator.add(5, 10);
System.out.println("Sum: " + result);
}
}

Static Method Hiding vs. Overriding


While static methods cannot be overridden, they can be hidden. If a subclass defines a
static method with the same name and parameters as the one in its superclass, it hides the
superclass method rather than overriding it.
Example of Method Hiding:
class Parent {
static void display() {
System.out.println("Static method in Parent class.");
}
}

class Child extends Parent {


static void display() {
System.out.println("Static method in Child class.");
}
}

public class StaticMethodHiding {


public static void main(String[] args) {
Parent p = new Parent();
p.display(); // Calls Parent's static method

Child c = new Child();


c.display(); // Calls Child's static method

Parent pc = new Child();


pc.display(); // Calls Parent's static method (not overridden)
}
}

Output:

Static method in Parent class.


Static method in Child class.
Static method in Parent class.

Key Differences Between final and static in Methods:
Aspect final Method static Method

Inheritance Cannot be overridden by Cannot be overridden, but can be


subclasses. hidden.

Object/Class Associated with object instances. Associated with the class itself.

Usage Used to prevent changes to Used for utility methods that don’t
method behavior. depend on object state.

Instance Access Can access instance variables Cannot access instance variables
Aspect final Method static Method

and methods. or methods.

● Use final methods when you want to prevent any modifications to the method’s
behavior in subclasses.
● Use static methods when the method’s functionality is tied to the class as a whole and
does not rely on object instances.

Do It Yourself

1. Write a Java program that demonstrates the use of the final keyword with methods.
Create a parent class with a final method and attempt to override it in the child class.
Explain why the program does or does not compile.Show a compilation error for the final
method being overridden and explain the error.
2. Create a Java program with a class that has both instance and static methods. Call the
static method without creating an instance of the class. Explain how static methods differ
from instance methods in terms of memory and access.
3. Write a Java program that declares a final method and a static method within the
same class. Inside the static method, attempt to modify a final variable. Explain why the
program does or does not allow modification of the final variable inside the static method

Quiz

1. What happens when you attempt to override a final method in a subclass?

A) The program runs normally.


B) The final method is successfully overridden.
C) The program compiles but throws an exception at runtime.
D) The program fails to compile with an error.
Answer: D) The program fails to compile with an error.

2. Which of the following is true about static methods in Java?

A) Static methods can be called without creating an instance of the class.


B) Static methods can access both static and instance variables directly.
C) Subclass methods can override static methods.
D) Static methods cannot return any value.

Answer: A) Static methods can be called without creating an instance of the class.

3. Given the following code, what will happen when the program is compiled?

class A {
public final void display() {
System.out.println("Final method in Class A");
}
}

class B extends A {
public void display() {
System.out.println("Trying to override final method");
}
}

A) The code will run and print "Trying to override final method."
B) The code will run and print "Final method in Class A."
C) The program will fail to compile with an error.
D) The code will throw a runtime exception.

Answer: C) The program will fail to compile with an error.

4. Which of the following statements is false regarding the static and final keywords
in methods?

A) A static method belongs to the class rather than to any specific object.
B) A final method cannot be overridden by a subclass.
C) A static method can be overridden in the subclass.
D) A final method can be called from the subclass but cannot be modified.

Answer: C) A static method can be overridden in the subclass.


5. Consider the following code snippet. What will be the output?

class Test {
static int count = 0;
Test() {
count++;
}
}

public class Main {


public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
System.out.println(Test.count);
}
}

A) 0
B) 1
C) 2
D) 3

Answer: D) 3

6. Given the following code, which statement is true?

class MyClass {
static void display() {
System.out.println("Static method called");
}
}

public class MainClass {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
MyClass.display();
}
}

A) The program will fail to compile.
B) The static method can only be called using the class name.
C) The static method can be called using both the class name and the object.
D) The static method cannot be called at all.

Answer: C) The static method can be called using both the class name and the object.

References

Recursive methods - Recursion in Java Full Tutorial - How to Create Recursive Methods
Nesting of methods - Java-70- Nesting of Methods in Java || Java Programming
Method overriding - #52 Method Overriding in Java
Method overloading Vs Method overriding - DIFFERENCES BETWEEN METHOD
OVERLOADING AND OVERRIDING - JAVA PROGRAMMING

Final and static methods - #57 Final keyword in java#4.6 Java Tutorial | Static Keyword

End of Session - 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy