Use of final keyword in java


Final Keyword

                Final keyword can be used with class, variable and methods


Final class

                Final class cannot be extended i.e. creating subclass is not allowed for final class.

Example:

final class Student
{
	// more code.
}

class Test extends Student // will create an compiler error
{

}

Final Method

                Final method cannot be overridden in its subclass. I.e. the method you have return should be used as it in your subclass without changing it

Example:

public class Student
{
	public int cube(int i)
	{
		return i * i * I;
	}
}

 

Final variable

                Final variable or we call this as a constant, it cannot be changed in any part of your code. Final keyword is applicable to all Example you can declare fields like

final float PI=3.14f;

 

Its good practice to add static keyword to a final member variable since all object created for that class will be have a same value.

static final PI=3.14f;




Comments


©candidjava.com