Non-static method:
Any method declared inside global area not prefix with static keyword is known as nonstatic method.
Note
Non static method is also known as nonstatic context.
Address of nonstatic methods will be stored inside object.
Every nonstatic context will be pointing towards object.
this:
- this is a keyword.
- this is a nonstatic reference variable.
- this will have address of current object.
- this variable can be used only inside nonstatic context.
- It cannot be used inside static context.
Program:
- class Mumbai
- {
- public void Sheela( )
- {
- System.out.println("Hi");
- System.out.println(this);
- System.out.println("Bye");
- public static void main(String [ ] args)
- {
- System.out.println(("MB");
- Mumbai ref = new Mumbai( );
- System.out.println(ref);
- ref.Sheela( );
- System.out.println(("ME");
- }
- }
Output:
MB
Sheela@1
Sheela@1
Hi
Sheela@1
Sheela@1
Bye
ME
ME
Note
1)How many ways we can used static member inside nonstatic context
>>>>>[ 3 times]
1.directly
2. Using classname
3. with the help of this
Program:
- class Mumbai
- {
- static int a=10;
- {
- public void Sheela( )
- {
- int a=15;
- System.out.println(a); //directly
- System.out.println(Sheela.a); //using classname
- System.out.println(this.a); //help of 'this'
- public static void main(String [ ] args)
- {
- Mumbai ref = new Mumbai( );
- ref.Sheela( );
- }
- }
Output:
15
10
10
10
2)How many ways we can used static member inside nonstatic context
>>>>>[ 3 times]
1.directly 2. with the help of this
Program:
- class Mumbai
- {
- static int a=10;
- {
- public void Sheela( )
- {
- int a=15;
- System.out.println(a); //directly
- System.out.println(this.a); //help of this
- public static void main(String [ ] args)
- {
- Mumbai ref = new Mumbai( );
- ref.Sheela( );
- }
- }
Output:
15
10
Why do we want this
>>whenever we have static variable and local variable with same
name inside nonstatic context we used this
1. If we used directly then high priority given to local variable.
2.To use nonstatic variable we need this as a reference.
0 Comments