non static Members:
Any member declared inside global area not prefix with static keyword known as non static member.
- class P1
- {
- public void test( )
- {
- }
- }
non static Variables:
Any global variable not prefix with static keyword is known as non static variable.
How many ways we can used static members inside context
2 ways > 1) directly 2) with the help of classname
Program:
- class P1
- {
- static int a=10;
- public void test( )
- public static void main(String [ ] args)
- {
- System.out.println("directly : "+a);
- System.out.println("Classname : "+P1.a);
- }
- }
Note:
1]We can not used nonstatic members inside static context.
1) Directly 2) With the help of classname
2]Non static members are stored inside object which is why programmer has to create object.
>>>By using new keyword
Program:
Syntax new classname( );
new:
- new is a keyword.
- new is an unary operator.
- new operator creates a block of memory inside heap area during run time.
- new operator returns address of an object which is created.
Note:
- For one class we can create n-number of objects.
- Whenever we write new keyword new object will be created.
Program:
- class Mob
- {
- public static void main(String [ ] args)
- {
- new Mob( );
- System.out.println(Mob ( ) );
- System.out.println(Mob ( ) );
- System.out.println(Mob ( ) );
- }
- }
Output:
Mob@1
Mob@2
Mob@2
Mob@3
How to store and print address:
- class Mob
- {
- public static void main(String [ ] args)
- {
- Mob xyz = new Mob( );
- System.out.println(xyz );
- System.out.println(xyz );
- System.out.println(xyz );
- }
- }
Output:
Mob@1
Mob@1
Mob@1
Mob@1
How to use nonstatic member inside static context
>>>>>>with the help of object reference
Program:
- class Mob
- {
- int a = 20;
- public static void main(String [ ] args)
- {
- Mob xyz = new Mob( );
- System.out.println(xyz.a);
- }
- }
Output:
20
How many times can we used static members inside static context
>>>>>>1)directly 2)help of classname 3)help of object reference
- class Mob
- {
- static int a = 20;
- public static void main(String [ ] args)
- {
- Mob xyz = new Mob( );
- System.out.println(a);
- System.out.println(Mob.a);
- System.out.println(xyz.a);
- }
- }
Output:
20
20
20
20
0 Comments