• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method calls to nonstatic methods

 
Olga Logan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I just got confused.... I have created a static method and called nonstatic method inside of it and it compiled.
Here is an example:
class A{
public final return getMethod(){
return 1;
}
}
class B {
public static A atest;
public static void testMethod(){
atest = new A();
atest.getMethod();
}
}
Why did it work?
Thanks,
Olga
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In order to invoke an instance method (non-static), you need to have an instance of the object to invoke the instance upon. You have that. You created an A object and referenced it with the variable atest. Now that you have that object, you are free to invoke any methods on it you want, static or not, no matter what context you are in, static or not.
I think the error you were expecting would be better illustrated by this:

I hope that helps,
Corey
 
Olga Logan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. It did help:-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic