Java Final Class

 FINAL:

This keyword is used to restrict the users.

It can be of many contexts.

It can be a variable, method, or class.


FINAL VARIABLE:

If you make any variable final you cannot change the value of final  variables.

  Declaration: final datatype var_name;

we can also assign values through constructor or direct initialization.

Example 01:

package Methods;

//Final Variables in Java


class Test

{

final int MIN=1;

final int NORMAL;

final int MAX;

Test(int normal) {

NORMAL = normal;

MAX =100;

}

void display()

{

System.out.println("MIN : "+MIN);

System.out.println("NORMAL : "+NORMAL);

System.out.println("MAX : "+MAX);

}

}


public class finalTest {


public static void main(String args[])

{

Test o =new Test(50);

o.display();

}

}


/*Final in Java can refer to variables, methods, and classes.

* The final keyword is used in several contexts to define an entity

that can only be assigned once.

* Once a final variable has been assigned, it always contains

the same value.


There are three simple rules :

The final variable cannot be reassigned

The final method cannot be overridden

Final class cannot be extended*/


FINAL METHODS:

If you make any method final we can’t override it.

  Declaration:

      final method_name(){//body}

Example 02:

package Methods;

//Final Methods in Java


class Super

{


public void display()

{

System.out.println("I am Super Display");

}

final void finalDisplay()

{

System.out.println("I am Super Final Display");

}

}


class sub extends Super

{


public void display()

{

System.out.println("I am Sub Display");

}

}


public class finalMethods {


public static void main(String args[])

{

sub o =new sub();

o.display();

o.finalDisplay();

}

}

/*We can declare a method as final, once you declare a method as final

it cannot be overridden.

* So, you cannot modify a final method from a sub-class.

* The main intention of making a method final would be that the content of the method should not be changed by any outsider.

*/


FINAL CLASS:

if you make any class final we can’t extend it

Declaration:

  final class classname

Example 03:

package Methods;

//Final Class in Java


final class finalClassDemo

{


public void display()

{

System.out.println("I am Display");

}

}


public class finalClasss{


public static void main(String[] args) {

finalClassDemo o =new finalClassDemo();

o.display();

}

}


/*When used in a class declaration, the final modifier prevents other classes from being declared that extend the class.

* A final class is a "leaf" class in the inheritance class hierarchy.


Example :

// This declares a final class

final class MyFinalClass

{

// statements

}

// Compilation error: cannot inherit from final MyFinalClass

class MySubClass extends MyFinalClass

{

// statements

}

*/


Post a Comment

0 Comments