wood burning stoves*
The moose likes Beginning Java and the fly likes Tormented by static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Tormented by static methods" Watch "Tormented by static methods" New topic
Author

Tormented by static methods

Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Hello comrade ranchers!
It's me. (I know, it's gettin' kinda annoyin')

I'm experiencing a lot of affliction and sorrow because I don't quite get how a non-static method can actually be called from a static context.
Let me indicate:



That thing above is totally allowed by the compiler, However this will make the compiler jump:



Could someone please explain me Why is it possible to call a non-static method from a static context by using a reference variable(as shown above)?

Good fortune to all of you!
Sincerely,
Jose
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30057
    
149

Jose,
The reference variable is what is giving you the context. var.method() means call method() on var. Just calling method() is equivalent to this.method() as there is an implicit "this" class unless you say otherwise. Since method() does not exist in the current class it chokes.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
how-do-you-do Jeanne!
thanks for the reply...

Sorry to admit it, but....

I'm still not gettin' it....
Adam Schaible
Ranch Hand

Joined: Oct 04, 2007
Posts: 101
I'll try to explain this, but someone may have to make another pass and clean up.

StaticTestDrive is NOT a static class, so when you create one, you have an instance of StaticTestDrive, which has the method m2. While you are in a static method (main), you may only other static methods, or methods from instance variables.

The same thing applies to other objects, consider:

public static void main(String[] args){

List myList = new ArrayList();
System.out.println(myList.size());

}

It's more confusing in your example, because it's incestuous - but it's the same to the language.

Once you instantiate a StaticTestDrive object, you've instantiated an object and are now eligable to call non-static methods on it.
Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Here I am. thank you for your reply sir,

While you are in a static method (main), you may only other static methods, or methods from instance variables.


What do you mean by saying I can call methods from instance variables?

*Could someone please tell me where can I find a tutorial or a book that instructs these rules...

I am so frustrated right now. I don't know how calling a non-static method from a static context using a class reference variable can make the compiler oversee the fact that it is non-static.

I will re-read the previous posts, and see If I can finally see how this works.

All the help is appreciated.
Best regards,
Jose
Jinny Morris
Ranch Hand

Joined: Apr 29, 2007
Posts: 101
Jose -

You have all my sympathy - since I beat my head against your exact question for MONTHS! And just recently had a flash of insight ... So I will try to elaborate on what Jeanne said without just confusing it.

Normally, you have to have an object in order to call a non-static method. So if you have a class Dog, with a method bark, then you have to first create a "Dog" object in order to get it to bark. But a static method, like main, doesn't know which of your Dogs you want to bark unless you explicitly tell it - so, if you first create a dog object in your main method, then you can tell it to bark. That's why this works



on the other hand, if in main you just say:



then there's no way to tell which Dog you want barking, or even if there's a Dog out there at all.

But since the only way you can get a non-static method to run is to have already created an object, that object is "understood" to be the one you want if you call another non-static method from within the first non-static method. That's the "understood" this that Jeanne used in her example this.method().

I hope this helps a little bit ... Good luck!
Michael Raymond Jr.
Ranch Hand

Joined: May 16, 2005
Posts: 178
Originally posted by Jeanne Boyarsky:
Jose,
The reference variable is what is giving you the context. var.method() means call method() on var. Just calling method() is equivalent to this.method() as there is an implicit "this" class unless you say otherwise. Since method() does not exist in the current class it chokes.



re: original poster
the implicit this that is on a method() call does nto work because it's a static method (the main method is static). just do a

new ClassName().method(); for a void method.

Or create and object reference as others have said.


explicit 'this'(somemethod) also is never allowed in static contexts.
[ October 05, 2007: Message edited by: Michael Raymond Jr. ]

Scooby Snacks for everyone...<br /> <br />SCJA, SCJP 1.4
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30057
    
149

Right. I didn't notice we were talking about a static method (main.) Thanks for clarifying that.
Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Good Morning Rancher Buddies !

I've been studying this minor programming case, and has already taken me more time than I had expected.

Well, let me examine my own Java-ic beliefs...

I know no non-static method can't be called without an object reference variable. (But there seems to be an exception)

I know there's no way to call a non-static method from a static method(context)

Originally posted by Jinny Morris:

But since the only way you can get a non-static method to run is to have already created an object, that object is "understood" to be the one you want if you call another non-static method from within the first non-static method. That's the "understood" this that Jeanne used in her example this.method().


Jinny, that's not exactly true, I could get a non static method to run by calling it from another method within the class

I'm burning my neurons here because no matter what, main() IS STATIC, and void method2() IS NON-STATIC,

And I don't see ANY clear rule that should theoretically allow method2() to be called from main()

So far I only Get:-- That by calling the non-static method using a reference variable, the context of the called method(s.method2())is no longer ruled by the context of the caller(main()) but by context of the reference variable(which belongs to a non-static class), right?

Sorry for all the inconveniences...
This is all so confusing.; well, at least to me, forgive my ignorance.
and..
A big thank you is what you all deserve, What would I be without this forum..
Sincerely,
Jose
Jinny Morris
Ranch Hand

Joined: Apr 29, 2007
Posts: 101
Jose - No, I don't think you're right on that. Even if you call your non-static method from another (static) method within the class, you still have to have created an object to call it with reference to (sorry about the grammar here!) For an example, main can be within the class; but I still cannot call a non-static method from main without having first created an object that main knows about - that is, by creating the object in main.

Why don't you try it? Define a class, define a static method other than main within that class, & try calling a non-static method of that class from your static method without creating an object. Bet the compiler won't let you do it ...

The clear rule that allows method2() to be called from main is to first create an object, then call the method on that object.
Ryan DeJana
Greenhorn

Joined: Sep 07, 2007
Posts: 9
Hi Jose,
Maybe this will help. The key here is having an instance of an object. In your example, within the main method, you created an instance of your class. An insance is allowed to call its own instance method.

So remember, regardless of the "static" context of a calling method, if an instance is created, that instance may call its own instance (and static) methods.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

I think I see the missing piece, so let me try this.

First, you need to consider how things work without being static.

As you probably realize, a class is a "blueprint" for creating objects. The class describes what an object "has" (variables) and what an object "does" (methods). When we say "new," it means make a new object based on this class. The object is an "instance" of that class (so the process of making the object is also called "instantiation").

"Instance variables" and "instance methods" are variables and methods that are specific to a particular instance. In other words, the class specifies that each object will have its own set of these variables and methods. So when referencing these, we need to identify the specific instance we're using -- for example, myInstance.var or myInstance.method().

Now, there's an important shorthand for this. If we're already inside the body of an instance method, there is an implicit variable "this" that references the calling instance. So inside an instance method, just calling "method1()" is implicitly "this.method1()."

With this in mind, let's consider the keyword "static."

If we declare a class member as "static," it means that the member stays with the class. In other words, a static member is not an instance member. When objects are created, they do not get their "own" static members. Instead, all instances share the static members in the class.

Because static members stay with the class, they can be accessed without identifying any particular instance. For example, if var is static, then we can (and should for the sake of clarity) access it using the class itself -- for example, MyClass.var. But note that we can access it using myInstance.var.

Because static members stay with the class, they are not associated with any calling object. Therefore, static methods do not have an implicit "this."

So if we're in a "static context" (for example, the body of a static method), and we simply call "method1()," then it is not implicitly "this.method1()" as it would be in an instance method. Instead, method1() must be reachable from a static (class) context. If it's not, that's when we get the error, "cannot be referenced from a static context," because we are not identifying an instance.
[ October 06, 2007: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jose Campana
Ranch Hand

Joined: May 28, 2007
Posts: 339
Greetings once more!
I'm astonished at your professionalism guys, I gotta say It's noticeable that you have studied way deeper into these concepts in comparison to me, and well, fortunately- because now I've understood the concepts through your points of view and knowledge.

Even though I've got this one figured out, I suppose my training is far from complete, but I must recognize your efforts to selflessly help java apprentices is the most valuable thing we learners can have.

marc, thank you for taking some of your precious time to write a detailed explanation. And to everyone, keep on going with the amazing job,

Sincerely, Jose
vaibhav panghal
Greenhorn

Joined: Feb 24, 2008
Posts: 25
great explanation marc . i too learnt some stuff . thank you .
 
Consider Paul's rocket mass heater.
 
subject: Tormented by static methods
 
Similar Threads
Anonymous Inner Class
inner classes
class defined inside an interface
How the increment work
Overriden Method Query