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.

like:

  1. variable

  2. method

  3. class

1) Java final variable

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

Example of final variable

There is a final variable limit, we are going to change the value of this variable, but it can't be change because final variables once assgined a value can nerver be changed.

public class FinalTest {
	private final int i = 90; //final variable

	public static void main(String[] args) {

	}

	public void run() {
		i = 12;
	}
}

 Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

public class FinalTest {
	public final void run(){
		System.out.println("running safely with 90kmph");
	}

}

class Honda extends FinalTest {
	@Override
	public void run() {
		System.out.println("running safely with 100kmph");
	}
	public static void main(String args[]) {
		Honda hd = new Honda();
		hd.run();
	}
}

 Output:Compile Time Error

3) Java final class

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

Example of final class

public final class FinalTest {
	public final void run(){
		System.out.println("running safely with 90kmph");
	}

}

class Honda extends FinalTest {
	public static void main(String args[]) {
		Honda hd = new Honda();
		hd.run();
	}
}

  Output:Compile Time Error

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it.

Q) What is blank or uninitialized final variable?

A final avariable that is not initialized at the time of declaration is known as blank final avariable.

If you want to create a variable that is initialized at the time of createing object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialize only in constructor.

Example of blank final method 

public class FinalTest {
	private final String panCard;
	public FinalTest(){
		panCard = "hagendasi";
	}

}

 static blank final variable

A static final avariable that is not initialized at the time of declaration is known as static blank final avariable. It can be initialized only in static block.

Example of blank final method

public class FinalTest {
	private static final String panCard;
	static {
		panCard = "staticBlock";
	}
	public static void main(String[] args) {
		System.out.println(FinalTest.panCard);
	}
}

Q) What is final parameter?

If you declare variable as final, you cannot change the value of it.

public class FinalTest {
	public static void main(String[] args) {
		FinalTest ft = new FinalTest(); 
		ft.finalParameter(5);
	}
	
	public void finalParameter (final int i) {
		i = i+1;
	}
}

 Output:Compile Time Error

Q) Can we declare a constructor final? 

No, because constructor is never inherited.

 

猜你喜欢

转载自www.cnblogs.com/chenqr/p/10369053.html