WHAT'S NEW?
Showing posts with label method. Show all posts
Showing posts with label method. Show all posts
final is a keyword in java. If anyone have knowledge of c++ then you can compare final with const keyword.
Why to mark a variable or method of nature final?

Its a simple requirement which states that,something should never change and in no way anybody should change it. For example value of PI is 3.142 which has not changed since it is discovered,so if we want to block the user or anyone from changing such values we should use final keyword.Assume if you are developing an application where you are working on a specific area of land so the limitations of the land can be valid candidate for being final.

Example of a final variable:
final int MAX=100;


  " Only once in the lifetime a final variable can be on left hand side later has to be on right hand side. "  



final keyword working


Convention for final variables.

Any variable which is declared as final should be written totally in UPPER CASE.

Here are some inbuilt final variables.
Math.PI
JFrame.EXIT_ON_CLOSE
BorderLayout.WEST.


A method can also be defined as final



public final void m1()
{
}

Any method declared as final cannot be overridden.
So if the scenario arises for restricting the access of method in super class to a sub class can be done by defining a method as final.

Also a class can be defined as final.

final class MyClass
{
}

Once a class is defined as final class, it cannot act as a super class to any other class.
This is used when a class has to be defined as a last class in th hierarchy, an is required that no other class extends it.
Defining a method in Java

Methods are considered as behavior in a Java Program.
Any changes to variables or any other objects in class are done using methods.

Structure of a method.

access-specifier return-type method-name(parameters)
{
}

Simple example of a method:

public void sayHello()
{
System.out.println("Hello Tom !!");
}

A method can have one or more parameters. 
Example consider a method to add two numbers

public void add(int num1,int num2)
{
int sum=num1+num2;
}

A method with return type void means that the method will not return anything, but if a method requires to return back something it will have return type other than void.
And a point to remember here is that it will require to include a return statement at the end of the method.
Or in simple words. IF A METHOD RETURN SOMETHING ,LAST STATEMENT IN THE METHOD WILL be the return statement.

Example of a method with return statement

public int square(int num)
{
int i=num*num;
return i;
}