Results 1 to 3 of 3

Thread: Need help

  1. #1
    captaincool is offline Member
    Join Date
    Mar 2011
    Posts
    1
    Rep Power
    0

    Default Need help

    Hi all,
    i just now started learning java. i went through Head First Java. but i am not able to understand static and non-static members and methods. can anyone plz tel why should we use static or non-static in code.


    Thanks

  2. #2
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default

    see the below code

    Java Code:
    public class RegexTest {
    
    	int i = 0;
    	//static int i = 0;
    
    	public static void main(String[] args) {
    		RegexTest obj1 = new RegexTest();
    		RegexTest obj2 = new RegexTest();
    		RegexTest obj3 = new RegexTest();
    		obj1.myMethod();
    		obj2.myMethod();
    		obj3.myMethod();
    	}
    
    	private void myMethod() {
    		
    		System.out.println("i value while entering = "+i);
    		i++;
    		System.out.println("i value while leaving = "+i);
    	}
    
    }
    I have declared an integer i.
    I have commented one line, a static integer i.

    First you execute this code and see the result. Then comment int i = 0 and uncomment static int i = 0 and see the result. Compare both. Then you'll understand why static variable :)

    Meanwhile I'll post about static methods

  3. #3
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default

    Hope you got the concept of static variable.
    Now static method is independent of instance. It is class specific.
    To access a static method you should use the class name, the dot operator and the method name.

    There are other restrictions also,
    a static method cannot access non-static variable (instance variable) directly.
    a static method cannot be over-ridden

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •