Results 1 to 4 of 4
Thread: static methods
- 12-30-2009, 01:50 PM #1
Member
- Join Date
- Dec 2009
- Posts
- 25
- Rep Power
- 0
static methods
Hello, I made a simple console program which has a main method and another method I'll call testMethod. If I call the method from inside main I get a compiler error about the testMethod not being static. If I make the method static all is well. I did not create the executing program using the new command but I would believe the object for the class is created when the program executes.
Please alleviate my confusion.
thanks
bill
- 12-30-2009, 01:57 PM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
You are best to read Sun's Java tutorial from the start. An instance of your class is created if you used the new keyword to create it. You can then call the instance methods on that instance. If you didn't create an instance in your code, only the class is loaded and that's why you can call the static methods (class methods).
- 12-30-2009, 02:29 PM #3gcampton Guest
what r0*x means is, if you try to call methods in other classes or even the same class as:
SomeMethod();
then those methods must be static, however nonstatic methods or also known as class member functions need to be created instances of them. eg.
There are various advantages and disadvantages to using static methods, as you will read in the tutorials.Java Code:public class StaticVsNot { public static void main(String[] args) { //first call to static method no instance is created. staticWelcome(); // create an instance of the class to call it's member functions. StaticVsNot svn = new StaticVsNot(); svn.nonStaticWelcome(); } public static void staticWelcome() { System.out.println("Static welcome"); } public void nonStaticWelcome() { System.out.println("normal welcome"); } }
You will have already used this using the Scanner class for reading input. Scanner classes methods are not static which is why you need to create an instance and to use dot notation.Last edited by gcampton; 12-30-2009 at 02:35 PM.
- 12-30-2009, 02:34 PM #4
Member
- Join Date
- Dec 2009
- Posts
- 25
- Rep Power
- 0
Similar Threads
-
Trouble with static methods and boolean equals() methods with classes
By dreamingofgreen in forum New To JavaReplies: 8Last Post: 04-16-2012, 11:00 PM -
Recursion with static and non static methods
By sh4dyPT in forum New To JavaReplies: 14Last Post: 03-27-2009, 06:56 AM -
Static methods
By carderne in forum New To JavaReplies: 10Last Post: 01-03-2009, 05:27 PM -
Static methods
By Java Tip in forum Java TipReplies: 0Last Post: 11-04-2007, 05:56 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks