0% found this document useful (0 votes)
3 views

Final Keyword In Java

The document explains the use of the 'final' keyword in Java, which restricts modifications to variables, methods, and classes. It also covers method overloading and overriding, highlighting their definitions, advantages, disadvantages, and differences, emphasizing their roles in enhancing code readability and flexibility. Additionally, it provides code examples to illustrate these concepts.

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Final Keyword In Java

The document explains the use of the 'final' keyword in Java, which restricts modifications to variables, methods, and classes. It also covers method overloading and overriding, highlighting their definitions, advantages, disadvantages, and differences, emphasizing their roles in enhancing code readability and flexibility. Additionally, it provides code examples to illustrate these concepts.

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Final Keyword in Java

 The final keyword in java is used to restrict the user. The java final keyword can be used in many
context.
Final can be:
 Variable
 Method
 class
 The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable.
 It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning of these. Let's first learn the basics
of final keyword.

Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
Example:
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");} }
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
} }
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


final class Bike
{
}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
} }
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){
System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running...
Java Method Overloading
Method overloading is a feature in Java that allows a class to have more than one method with the same name,
provided their parameter lists are different. Itenables methods to perform similar but distinct tasks. Method
overloading is a form of compile-time polymorphism, meaning that the compiler determines which method to
call based on the method signature (name and parameter list).

For example,

class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
File Name: Calculator.java

public class Calculator {


// Method to add two integers
public int add(int a, int b) { // Method named 'add' that takes two integer parameters
return a + b; // Returns the sum of the two integers
}
// Method to add three integers
public int add(int a, int b, int c) { // Overloaded method named 'add' that takes three integer parameters
return a + b + c; // Returns the sum of the three integers
}
// Method to add two double values
public double add(double a, double b) { // Overloaded method named 'add' that takes two double parameters
return a + b; // Returns the sum of the two double values
}
// Method to add three double values
public double add(double a, double b, double c) { // Overloaded method named 'add' that takes three double para
meters
return a + b + c; // Returns the sum of the three double values
}
// Method to add an array of integers
public int add(int[] numbers) { // Overloaded method named 'add' that takes an array of integers as parameter
int sum = 0; // Initializes sum to 0
for (int number : numbers) { // Iterates through each element in the array
sum += number; // Adds each element to the sum
}
return sum; // Returns the total sum of the elements in the array
}
// Main method to test the overloaded methods
public static void main(String[] args) { // Main method, the entry point of the program
Calculator calc = new Calculator(); // Creates an instance of the Calculator class
// Test add methods
System.out.println("Sum of 2 and 3 (int): " + calc.add(2, 3)); // Calls the add method with two integers and prints t
he result
System.out.println("Sum of 1, 2, and 3 (int): " + calc.add(1, 2, 3)); // Calls the add method with three integers and
prints the result
System.out.println("Sum of 2.5 and 3.5 (double): " + calc.add(2.5, 3.5)); // Calls the add method with two doubles
and prints the result
System.out.println("Sum of 1.1, 2.2, and 3.3 (double): " + calc.add(1.1, 2.2, 3.3)); // Calls the add method with thr
ee doubles and prints the result
System.out.println("Sum of array {1, 2, 3, 4, 5}: " + calc.add(new int[]{1, 2, 3, 4, 5})); // Calls the add method with
an array of integers and prints the result
}
}
Output:

Sum of 2 and 3 (int): 5


Sum of 1, 2, and 3 (int): 6
Sum of 2.5 and 3.5 (double): 6.0
Sum of 1.1, 2.2, and 3.3 (double): 6.6
Sum of array {1, 2, 3, 4, 5}: 15

Advantage of Method Overloading


1. Enhanced Readability: By using the same method name for similar operations, method overloading reduces
complexity and makes the code easier to understand.
2. Code Reusability: Developers can reuse the logic of overloaded methods with different parameter
combinations, eliminating the need to duplicate entire methods.
3. Flexibility: Method overloading offers the flexibility to select the appropriate method to execute based on the
passed parameters.
4. Simplified Interfaces: By consolidating similar operations under a single method name, overloading methods
simplify class interfaces.
5. Improved Maintainability: Overloading helps avoid creating multiple methods with different names, making
the code easier to maintain and less prone to errors.
6. Increased Developer Productivity: Overloading reduces the time spent on method naming, allowing
developers to focus more on implementing core logic.
7. Code Consistency: Using overloaded methods maintains consistency across the codebase, making it easier
for other developers to understand and work with the code.
8. Clear Intent: Overloaded methods clearly convey the purpose of the code by using the same method name,
indicating similar functionality.
9. Parameter Convenience: Overloading methods provide a variety of parameter options, making it convenient
for users of the class or library.
10. Polymorphism: Method overloading is a key aspect of polymorphism, enabling different behavior based on
the context of method invocation.

Disadvantages of Method Overloading


1. Ambiguity: Poorly designed overloaded methods can create ambiguity, making it difficult for the compiler to
determine which method to call.
2. Increased Complexity: Overloading methods with various parameters or complex types can complicate the
code, making it harder to understand and maintain.
3. Overuse: Excessive use of method overloading can lead to convoluted code and reduce its readability.
4. Learning Curve: Beginners may find it challenging to grasp the concept of method overloading and might
struggle to differentiate between overloaded methods.
5. Efficiency Concerns: If not implemented carefully, method overloading can result in redundant computations
or excessive memory usage.
6. Naming Challenges: Finding suitable names for overloaded methods can be difficult, as the names should
accurately reflect the differences in parameter combinations.
7. Type Differentiation Limitations: Method overloading cannot differentiate methods based solely on return
type, potentially causing confusion.
8. Increased Compilation Time: Having many overloaded methods can lead to longer compilation times.
9. Compatibility Issues: Modifying or extending existing code with overloaded methods can introduce
compatibility issues if the code relies on specific method signatures.
10. Debugging Complexity: Debugging code with overloaded methods can be more complex, requiring careful
consideration of which overloaded method is being executed.

Java Method Overriding


Method overriding is a fundamental concept in object-oriented programming (OOP) that allows a subclass to
provide a specific implementation for a method that is already defined in its superclass. It enables a subclass to
inherit the method from the superclass but override it to perform a different task. Method overriding is essential
for achieving runtime polymorphism, where the method that gets called is determined by the actual object type
at runtime, not the reference type.

For example,

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
File Name: MethodOverriding.java

// Superclass Animal
class Animal {
// Method to be overridden in subclass
public void makeSound() {
System.out.println("Animal makes a sound"); // Prints a generic animal sound message
}
}
// Subclass Dog that extends Animal
class Dog extends Animal {
// Overriding the makeSound method in the superclass
@Override
public void makeSound() {
System.out.println("Dog barks"); // Prints a specific message indicating a dog barking
}
}
// Main class to test method overriding
public class MethodOverriding {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create an Animal object and assign it to a variable of type Animal
Animal myDog = new Dog(); // Create a Dog object but reference it as an Animal type
// Call makeSound method on both objects
myAnimal.makeSound(); // Calls the makeSound method of the Animal class, prints "Animal makes a sound"
myDog.makeSound(); // Calls the overridden makeSound method of the Dog class, prints "Dog barks"
} }
Output:

Animal makes a sound


Dog barks

Advantages of Method Overriding


1. Polymorphic Behavior: Method overriding facilitates polymorphism, enabling objects from different classes
to be treated uniformly based on their common parent class.
2. Customized Functionality: Subclasses can provide their own implementations of inherited methods through
overriding, allowing them to tailor functionality to meet specific requirements.
3. Code Extensibility: Overriding methods allows the functionality of the parent class to be extended without
altering its existing code.
4. Fine-tuning Behavior: Developers can refine the behavior of inherited methods to address specific use cases
by overriding them.
5. Code Reusability: By inheriting and selectively modifying or extending the functionality of the parent class,
method overriding promotes code reuse.
6. Flexibility in Method Invocation: Overriding allows developers to call the same method on different objects,
with each object executing its specific implementation.
7. Dynamic Method Dispatch: Overriding methods enable dynamic method dispatch, determining the
appropriate overridden method at runtime based on the actual type of the object.
8. Encapsulation: Method overriding can help enforce encapsulation by controlling the accessibility and
behavior of methods in subclasses, ensuring appropriate data manipulation.
9. Framework Customization: In frameworks or libraries, method overriding allows developers to adapt and
customize the behavior of predefined methods to meet their specific needs.
10. Enhanced Code Modularity: By encapsulating specific functionality within subclasses, method overriding
promotes modularity, making the codebase more manageable.

Disadvantages of Overriding
1. Inconsistent Behavior: Poor implementation of method overriding can result in inconsistent behavior across
subclasses, complicating code comprehension and debugging efforts.
2. Fragile Base Class Problem: Alterations in the behavior of overridden methods in the parent class can
inadvertently impact the functionality of subclasses.
3. Tight Coupling: Method overriding can create tight coupling between parent and child classes, potentially
reducing flexibility and ease of maintenance.
4. Access Control Limitations: Overridden methods must have the same or less restrictive access modifiers
than the original method, which can limit access control options.
5. Misuse of Inheritance: Method overriding can be misused, leading to overly complex inheritance hierarchies
or inappropriate parent-child relationships.
6. Runtime Performance Impact: Overriding methods can introduce slight performance overhead due to the
dynamic dispatch mechanism used to determine the correct method at runtime.
7. Method Signature Constraints: Overridden methods must maintain the same method signature as the
original method, restricting changes to parameters or return type.
8. Difficulty in Method Hiding: Overridden methods can hide static methods with the same name in the parent
class, causing confusion and potential runtime errors.
9. Limited Method Combination: Overriding methods cannot combine the behavior of multiple parent class
methods, as only a single overridden method can exist.
10. Complexity in Method Chains: Method overriding can introduce complexities in method chaining scenarios,
potentially leading to unexpected results or incorrect behavior.

ethod Overl Method Overloading Method Method Overriding


Method overloading is used to increase the readability of Method overriding is used to provide the
the program. specific implementation of the method that is
already provided by its super class.

Method overriding occurs in two classes that


Method overloading is performed within class.
have IS-A (inheritance) relationship.

In case of method overloading, parameter must be In case of method overriding, parameter must
different. be same.

Method overloading is the example of compile time Method overriding is the example of run time
polymorphism. polymorphism.

In Java, method overloading cannot be performed by


changing return type of the method only. Return type can Return type must be same or covariant in
be same or different in method overloading. But you must method overriding.
have to change the parameter.

It uses static binding. It uses dynamic binding.

It provides specific implementation of the


It enhances code readability.
method that is provided by the parent class.

If any error occurs, can be caught at compile-time. If any error occurs, can be caught at run-time.

It is applicable to both private and final methods. It is not applicable to private and final methods.

It is called early binding. It is called late binding.

Static method can be overloaded. Static method cannot be overridden.

Implemented in single class. Implemented in two classes.

You might also like