The final keyword

First, we will create a new class. If we declare any variable as final, that means the value cannot be changed again. Let's consider the following code:

package coreJava;

public class finaldemo {

public static void main(String[] args) {
//TODO Auto-generated method stub
final int i=4; //constant variables
}
}

As you can see, we have declared the integer value as 4. This means we cannot change this value to another number. If we try to do that, it throws an error saying Remove 'final' modifier of 'i'. This keyword is useful if we want a value to be constant. 

If we mark a class as final, it will throw an error because when we change the access mode to final, we are not able to use that as a parent class. In other words, we will not be able to inherit our properties from it. If we want to inherit our properties, we need to change it back to public. The key logic for the final keyword is that, once written, we cannot override final methods. So these are unique and cannot be used again with the same name.

The final keyword can be used at the method level to make sure that the method is not overridden. It is used at the variable level to make sure we're not changing it, and it can also be used at the class level to ensure that we are not inheriting that parent class.

But remember not to confuse final and finally. finally is something that is related to try...catch exceptions. Once you execute the try or catch block, and preface any error, the controller will still come to this log and execute the code, no matter whether the script is pass or fail. finally is all about restricting access, such as we cannot use that, inherit that, or even change the values. We have explored packages, and how to import packages into other classes. We have explored the inheritance of interfaces, runtime polymorphism, strings, and many more. This is all about keywords.

In the next section, we will learn about packages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.209