Sunday, 30 April 2023

What is Final Keyword in Java? with example.



In Java, the "final" keyword is used to create constants, mark methods as non-overridable, and prevent classes from being extended. Here are some examples of how the "final" keyword is used in Java:


1. Creating Constants: You can use the "final" keyword to create constants that cannot be changed during the execution of a program. For example:


```

final double PI = 3.14159;

final int MAX_VALUE = 100;

```


In the above example, "PI" and "MAX_VALUE" are constants that cannot be changed once they are initialized.


2. Non-Overridable Methods: You can use the "final" keyword to mark a method as non-overridable, which means that subclasses cannot override the method. For example:


```

class Parent {

    final void print() {

        System.out.println("This is a parent method.");

    }

}


class Child extends Parent {

    // This will generate a compile-time error

    void print() {

        System.out.println("This is a child method.");

    }

}

```


In The Above Example, The "Print" Method In The "Parent" Class Is Marked As Final, Which Means That It Cannot Be Overridden In The "Child" Class.

3. Preventing Classes From Being Extended: You Can Use The "Final" Keyword To Prevent A Class From Being Extended, Which Means That Subclasses Cannot Be Created. For Example:


```

final class MyClass {

    // Class members

}


class MySubClass extends MyClass {

    // This will generate a compile-time error

}

```


In the above example, the "MyClass" class is marked as final, which means that it cannot be extended by any subclasses.


In Summary, The "Final" Keyword Is A Powerful Tool In Java That Can Be Used To Create Constants, Mark Methods As Non-overridable, And Prevent Classes From Being Extended. By Using The "Final" Keyword, You Can Make Your Code More Efficient, Secure, And Easy To Understand.

No comments:

Post a Comment

What is Java Permutation and Combination Program?

Here's A Java Program That Calculates Permutations And Combinations: ```Java Import Java.Util.Scanner; Public Class Permutationcombinati...