Wednesday, 18 June 2014

STATIC KEYWORD AND FINAL KEYWORD

STATIC KEYWORD :


Consider the following program

     class Print
    {
static int a;
int b;
void get(int a,int b)
{
this.a=a;
this.b=b;

}

void op()
{
System.out.println(a+""+b);

}
public static void main(String args[])
{
Print p=new Print();
p.get(10,20);
Print p1 = new Print();
p1.get(30,40);
p.op();
p1.op();
}
    }

Static keyword is used in three ways :
  • Static Variable.
  • static Method.
  • Static Block.
STATIC VARIABLES : 
In static Variable , if we declare the value of any variable as static , the value of this variable remains same throughout the program and it takes in the value which is declared first via object . In other words , once assigned a value anywhere in the program it cannot be changed 

STATIC METHODS :

Static methods always contain static properties .
Consider the following program :

class Print
{
Static int a=10;
public static void main(String args[])
{
System.out.println(Print.a);
}
}

We can acess static variables and methods with class name only.

STATIC BLOCK :

Static block always run first even before the main method.

class Print
{
Static 
{
System.out.println("A");
}
public static void main(String args[])
{
System.out.println("B");
}
}

It will print A first and then will print B.

FINAL KEYWORDS :

Final keywords are of following types :
  • Final Variable
  • Final Method
  • Final Class

FINAL VARIABLE :

Consider the following set of codes :

 final int a=10;

The variable a is fixed now and remains same throughout the program . If you intend to change the value of  a Final variable ,compile time error is thrown by the compiler .
  
FINAL METHOD :

If we declare a method as final method , then we cannot override that method .

public class Base
{
    public       void m1() {...}
    public final void m2() {...}
 
    public static       void m3() {...}
    public static final void m4() {...}
}
 
public class Derived extends Base
{
    public void m1() {...}  // Ok, overriding Base#m1()
    public void m2() {...}  // forbidden
 
    public static void m3() {...}  // OK, hiding Base#m3()
    public static void m4() {...}  // forbidden
}

FINAL CLASS :

If we declare a class a final class , then we cannot inherit a class into other  class .
Example : System String are the classes declared final at back end .

NOTE :

If we declare a class 1 as final class then its method cannot be overridden in other class 2 because we cannot inherit class 1 in class 2>
Therefore no overridden .  

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | coupon codes