Date 2-august-2016
1.
Static method
Static method is a java method, it will be
recognized and executed at the time of calling that static method.
Static methods are able to allow only
static members of the current class, static methods are not allowing non-static
members of the current class.
If we want to access non-static members in
static member then we have to create object for the respective class and we
have to use the generated reference variable.
In java applications, we are able to access
static methods either by using reference variable or by using class name
directly.
In java applications, if we access instance
methods by using a reference variables having null value the JVM will rise an
exception like “java.lang.NullPointException”, but, if we access static methods
by using reference variable having null; value then JVM will not rise
exception.
Static methods are not allowing “this”
keyword in their implementation, but, to access current class static methods,
we can use “this” keyword.
Ex code:-
class A
{
int i=10;
static
int j=20;
static
void m1()
{
System.out.println("m1-A");
//System.out.println(i);
---->Error
System.out.println(j);
//System.out.println(this.j); ---->Error
A
a=new A();
System.out.println(a.i);
}
void
m2()
{
System.out.println("m2-A");
this.m1();
}
}
class Test
{
public
static void main(String[] args)
{
A
a=new A();
a.m1();
A.m1();
a.m2();
A
a1=null;
//a1.m2();--->NullPointerException
a1.m1();
}
}
Output:-
m1-A
20
10
m1-A
20
10
m2-A
m1-A
20
10
m1-A
20
10
No comments:
Post a Comment