• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

lil confused!!

 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi for the below code,

class MethodInvocation
{

int a=10;
int b=10;

void add()
{
System.out.println(a+b);
}

public static void main(String[] args)
{
//new MethodInvocation().add();
MethodInvocation obj = new MethodInvocation();
obj.add();
obj.a = 10;
//add(); --------> Why this won't work giving the error non-static method cannot be referenced from a static context?/
}
}


1). Why would the bolded part not work while obj.add() does the same thing and works fine?/ I understand the error but then why does obj.add() work?/

2). Execution of a program starts from main() method and ends in main() method right?/

Thanks.

[ February 06, 2008: Message edited by: Arjun Reddy ]

[ February 06, 2008: Message edited by: Arjun Reddy ]
[ February 06, 2008: Message edited by: Arjun Reddy ]
 
Jeff Storey
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arjun,

The reason you get that error message is because the main method is a static method, where add is not. What this means is that you need an instance of MethodInvocation to be able to invoke the add method (which is why the first case works). If you made the add method static by doing something like:

it would fine (in fact you would not want to call obj.add since you would be calling a static method on an instance variable). Bottom line is static methods and variables do not require and instance of the obj where non-static does.

Hope this helps,
Jeff
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeff for the reply.

So, non-static methods can still be accessed from static context but with an object reference right?/

Also, can some one answer my second question please?

Thanks.
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure exactly what you're asking in the second question. The main method is executed if you run an application, but it's neither necessarily the first code to run (there might be static initializers) nor necessarily the last (the code may spawn threads that keep running after main has finished).
 
Arjun Reddy
Ranch Hand
Posts: 629
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats what I actually wanted to know. Thanks guys for all ya answers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic