aspose file tools*
The moose likes Beginning Java and the fly likes lil confused!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "lil confused!!" Watch "lil confused!!" New topic
Author

lil confused!!

Arjun Reddy
Ranch Hand

Joined: Nov 10, 2007
Posts: 629
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 ]

Be Humble... Be Nice.
Jeff Storey
Ranch Hand

Joined: Apr 07, 2007
Posts: 230
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

Joined: Nov 10, 2007
Posts: 629
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
Marshal

Joined: Mar 22, 2005
Posts: 42913
    
  68
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

Joined: Nov 10, 2007
Posts: 629
Thats what I actually wanted to know. Thanks guys for all ya answers.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: lil confused!!