What is final function in java

final method in java

In Java, the final keyword is one of the most important concepts. Many programmers may have a lot of doubts in mind. I have heard many time common questions about the final keyword like How to make a final method? When to create a method final? What is the need to make a final method? We have already covered the final variable in java in a separate topic. In this topic, we will learn all about the final method.

What is the final method in Java?

A final keyword can be applied to a variable, method, or class. I have seen in the previous post how the final variable is used in java and applied some restrictions to the user. When we use the final keyword with the method, JVM applies restriction to the method.

We can declare a method in a class with the final keyword. A method declared with the final keyword is called the final method. A final method can’t be overridden in subclasses. Whenever we define a final keyword with a method, the final keyword indicates to the JVM that the method should not be overridden by subclasses.

In Java, there are many classes that have final methods and they are not overridden in subclasses. In Java, the Object class have notify() and wait() method are final methods. The final method enforces the subclasses to follow the same implementation throughout all the subclasses.

NOTE: The final method always binds at compile time in java. It is much faster than non-final methods because they are not required to be resolved during run-time.

accessModifier final returnType methodName() < //Body of method >

Here accessModifier specifies the scope of the method. You can read about access modifiers.
final is a keyword that is used to make a final method.
returnType is the type of data that you want to return from the method.
methodName is the name of the method.

public final void showData() < // Body of method >

How to use the final method

We must declare methods with the final keyword if we require to follow the same implementation throughout all the derived classes. By use of the final method, we can apply the restriction in inheritance.

class ParentClass < final void showData() < System.out.println("This is a final method of Parent class"); >> class ChildClass extends ParentClass < // It will throw compliation error final void showData() < System.out.println("This is a final method of Child class"); >> class MainClass < public static void main(String arg[]) < ParentClass obj = new ChildClass(); obj.showData(); >>

Output: Compilation error

Important points about the final method

The final method with the private keyword

A private and final should not use together with a method because it doesn’t make any sense. Because private methods of the superclass are not inherited in subclasses and they act like a final method.

The final method with the static keyword

As you already know we can’t override a static method in subclasses. If we try to override a static method, then it is known as method hiding. So, we should not make the static final method in java because both keywords don’t create value together.

Читайте также:  Solution file in java

The final method with abstract keyword

A method declared without a body is an abstract method. We declare the abstract method only when we require just method declaration in Parent classes and implementation will provide by child classes. We can’t use the final keyword with abstract methods because both concepts contradict each other.

Performance

The final method always binds at compile time. The compiler knows that final methods can’t be overridden in derived classes. These methods provide better performance than nonfinal methods.

When to use the final method?

When you want to apply restrictions on the method. It means that no one can’t change the definition of the final method in the derived classes. Let’s say you want to provide any important or secure information in the method so you can make it the final method. So that any derived class can’t override it or manipulate the information of the method.

Let’s take an example of the sensitive data of the office. In the office, there may be some data that are not accessible to each employee. So these types of data should be restricted.

class OfficeData < void policy() < System.out.println("There are three policies"); >final void financial() < System.out.println("Offic financial data"); >> public class Record extends OfficeData < public void mainRecord() < System.out.println("All data record of office"); >@Override void policy() < System.out.println("Adding one more policy"); >public static void main(String arg[]) < Record record = new Record(); record.mainRecord(); record.policy(); >>

Output: All data record of office
Adding one more policy

Источник

Вот так final…

Java-университет

Вот так final… - 1

В java есть ключевое слово – final . Оно может применяться к классам, методам, переменным (в том числе аргументам методов). Для класса это означает, что класс не сможет иметь подклассов, т.е. запрещено наследование. Это полезно при создании immutable (неизменяемых) объектов, например, класс String объявлен, как final .

 public final class String < >class SubString extends String < //Ошибка компиляции >

Следует также отметить, что к абстрактным классам (с ключевым словом abstract ), нельзя применить модификатор final , т.к. это взаимоисключающие понятия. Для метода final означает, что он не может быть переопределен в подклассах. Это полезно, когда мы хотим, чтобы исходную реализацию нельзя было переопределить.

 public class SuperClass < public final void printReport()< System.out.println("Report"); >> class SubClass extends SuperClass < public void printReport()< //Ошибка компиляции System.out.println("MyReport"); >> 

Для переменных примитивного типа это означает, что однажды присвоенное значение не может быть изменено. Для ссылочных переменных это означает, что после присвоения объекта, нельзя изменить ссылку на данный объект. Это важно! Ссылку изменить нельзя, но состояние объекта изменять можно. С java 8 появилось понятие — effectively final . Применяется оно только к переменным (в том числе аргументам методов). Суть в том, что не смотря на явное отсутствие ключевого слова final , значение переменной не изменяется после инициализации. Другими словами, к такой переменной можно подставить слово final без ошибки компиляции. effectively final переменные могут быть использованы внутри локальных классов ( Local Inner Classes ), анонимных классов ( Anonymous Inner Classes ), стримах (Stream API).

 public void someMethod() < // В примере ниже и a и b - effectively final, тк значения устанавливаютcя однажды: int a = 1; int b; if (a == 2) b = 3; else b = 4; // с НЕ является effectively final, т.к. значение изменяется int c = 10; c++; Stream.of(1, 2).forEach(s->System.out.println(s + a)); //Ок Stream.of(1, 2).forEach(s-> System.out.println(s + c)); //Ошибка компиляции > 
  1. Что можно сказать про массив, когда он объявлен final ?
  2. Известно, что класс String — immutable , класс объявлен final , значение строки хранится в массиве char , который отмечен ключевым словом final .
 public final class String implements java.io.Serializable, Comparable, CharSequence < /** The value is used for character storage. */ private final char value[]; 
  1. Т.к. массив – это объект, то final означает, что после присвоения ссылки на объект, уже нельзя ее изменить, но можно изменять состояние объекта.
 final int[] array = ; array[0] = 9; //ок, т.к. изменяем содержимое массива – array = new int[5]; //ошибка компиляции 
 import java.lang.reflect.Field; class B < public static void main(String[] args) throws Exception < String value = "Old value"; System.out.println(value); //Получаем поле value в классе String Field field = value.getClass().getDeclaredField("value"); //Разрешаем изменять его field.setAccessible(true); //Устанавливаем новое значение field.set(value, "JavaRush".toCharArray()); System.out.println(value); /* Вывод: * Old value * JavaRush */ >> 

Обратите внимание, что если бы мы попытались изменить подобным образом финальную переменную примитивного типа, то ничего бы не вышло. Предлагаю вам самостоятельно в этом убедить: создать Java класс, например, с final int полем и попробовать изменить его значение через Reflection API. Всем удачи!

Читайте также:  Html link min width

Источник

Оцените статью