• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

static method calls to nonstatic methods

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you. It did help:-)
 
reply
    Bookmark Topic Watch Topic
  • New Topic