Sunday 9 June 2013

Static,non-static and final

Static variable

In Java, a static member is a member of a class that isn’t associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.

The two types of static members are static fields and static methods:
Static field: A field that’s declared with the static keyword, like this:
Syntax:
private static int counter;
The value of a static field is the same across all instances of the class.

Static method

A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.

Non-static method

A method in Java is a block of statements that has a name and can be executed by calling (also called invoking) it from some other place in your program. Along with fields, methods are one of the two elements that are considered members of a class. (Constructors and initializers are not considered class members.)
Syntax: 
visibility [static] return-type method-name (parameter-list)
{
statements...
}


Final Keywords

A java variable can be declared using the keyword final. Then the final variable can be assigned only once.
A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.
Java classes declared as final cannot be extended. Restricting inheritance!
final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding.


EmoticonEmoticon