This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

statin vs. nonstatic methods

 
Ravindra
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends,
this one is from a site (of 3 peoples, one was raji or so , I don't remember the exact names)
"Any non-static method will throw a NullPointerException if the calling object reference is null, static methods are ok."
I can't understand the meaning of the statement.
anyone pls help.
thanks in advance,
Ravindra..
[This message has been edited by Ravindra (edited August 20, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am by no means an expert, but I believe what they are saying is to call a non-static method of an object, the object must live somewhere (i.e. someone called new xxx() ). Static methods do not require this because they only operate on "static" data which is created when a class is loaded.
Here's a simple example:
public class MyClass {

static int a = 0;
int b = 1;

static void int getA() {
return a;
}

void int getB() {
return b;
}
public static void main(String args[]) {
int myInt = 0; //must initialize variables inside methods
myInt = MyClass.getA(); // can call this because it's static
MyClass mc; // mc is initialized to null (default of objects)
myInt = mc.getB(); // this is an error: no instance of MyClass loaded yet
mc = new MyClass(); //normally you would call this at declaration

myInt = mc.getB(); // now it's okay
}
}

Hope that helps.
Chris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic