*
The moose likes Beginning Java and the fly likes Static vs non static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static vs non static" Watch "Static vs non static" New topic
Author

Static vs non static

thom lamb
Greenhorn

Joined: May 25, 2002
Posts: 1
I will demonstrate my ignorance w/ this ? Im sure
why doesn't this work
public class Something(){
public static void main(){}
Something something = new Something();
public void someMethod(){
otherClass.otherMethod(){}
}
class otherClass{
public otherMethod(){}
}
It keeps saying static method called from nonstatic, I know I am missing some grand philosophy of Java despite having read over and over again about classes and static modifiers etc.
Can someone please enlighten me, I'm starting to go crazy over this... #)
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205


It keeps saying static method called from nonstatic, I know I am missing some grand philosophy of Java despite having read over and over again about classes and static modifiers etc.
Can someone please enlighten me, I'm starting to go crazy over this...


Well first, I see a problem with the way otherMethod() is defined. It's not a constructor, so you need to declare its return type. I'm guessing it's void, so you should re-write it as:
public void otherMethod(){}
Also, naming conventions are important for communication with other Java developers, so your other class should be named OtherClass. (All reference types should begin with an initial capital letter).
Now, assuming this change, your line in someMethod() woud be:
OtherClass.otherMethod();
Here you are using the class name to invoke a method on it. The only way this is legal is if otherMethod() is declared as static. Otherwise, you need an actual instance of the class in order to invoke a method on it. You can do one of two things.
1) Instantiate an OtherClass object and call its otherMethod() method:
OtherClass myOtherClassReference = new OtherClass();
myOtherClassReference.otherMethod();
OR
2) Declare otherMethod() to be static:
public static void otherMethod() {}
Either will fix your code.
One more thing, "thom":
Please change your name to comply with the naming policy to which you agreed when you registered here..

For your publicly displayed name,
use a first name, a space, and a last name.

You can change your name here:
here

You can also find the naming policy here:
http://www.javaranch.com/name.jsp
Thank You!
[ May 25, 2002: Message edited by: Rob Ross ]
[ May 25, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static vs non static
 
Similar Threads
overridding doubt
can't run
invoking method by refrence
static method in abstract class