Technology : General Technology Notes: Diary of a late,late adopter.
Updated: 4/4/2004; 7:43:40 AM.

 

Frequent Visits

Subscribe to "Technology" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.

 
 

Wednesday, March 17, 2004

Static

 

1 exerting force by reason of weight alone without motion

2 showing little change

  • An early frustration in learning Java is the error:   non-static method foo( ) cannot be referenced from a static context
  • Perhaps you are trying to call a simple method of your class from the main() method.  The main method is a static context.  The quick solution is to instatiate your object with MyObject mo = new MyObject right inside your main method.  now you have an instance of MyObject  
  • A static variable or method is going to persist across all the objects instantiated.
  • Static means that you lose the use of the 'this' keyword because the use of 'this' implies that you have an instantiation of an object.
  • Static means that it doesn't depend on the instantiation of an instance of the object. It still exists and can be called from an instance of the object, but it can also be called without creating the object.
  • The main() method is static because you have to call it to start a java program. That is, you call it before any objects are instantiated.
  • Consider the following class: 
    public class AddMe{
    	
    	static int num = 100
    	
    	static int add(int i){
    		int sum = i+2;
    		return sum;
    	}
    }
    
  • When I want to access the variable num, I can just say, myNum = AddMe.num and get the number 100.
  • I can also instantiate AddMe am = new AddMe() and then call myNum = am.num with the same effect.
  • Same with the add method. myNum = AddMe.add(2) sets myNum to 4 and so does myNum = am.add(2)
  • During my one week java class from Sun, I completed an exercise by using all static methods. I could then call the methods just like I made function calls in PHP or VB. My solution was used as an example of bending Java to act like a procedural language. Which, in case you need to be told, was frowned upon. It avoids all the Object Oriented concepts of Java. You don't even ever need to instantiate a class!

6:55:17 PM    comment []

© Copyright 2004 mcgyver5.



Click here to visit the Radio UserLand website.

 


March 2004
Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
Feb   Apr