i have studied that a static method or variable is always associated with the class and can not be accessed with the object reference. i was trying this in a program, but the object of the class in which static is defined is able to acces the method. how is this possible. pl. clearify my problem and about static method and static class. the code is as follows -
Accessing static members in a static way (using the clas name) is the preferred way to do it. Why? It's mainly a matter of clarity -- accessing the static members the other way is misleading because it looks like you are acting on the given object.
Originally posted by Jesper de Jong: Yes, you can access a static method or member variable through an instance.
Does anybody know why this is allowed in Java? I can't think of any example that demonstrates why it would ever be necessary to do this. In my opinion, this should have been made illegal in Java.
I agree that it should have been illegal. The problem is that the method that gets invoked is the one in the compile-time type of the instance, whereas a casual reader of the code (not realising that the method is static) would think that the run-time type is used.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Originally posted by Peter Chase: I agree that it should have been illegal. The problem is that the method that gets invoked is the one in the compile-time type of the instance, whereas a casual reader of the code (not realising that the method is static) would think that the run-time type is used.
As an example of what's misleading about this syntax, consider the following. Will running Test's main load class B into the JVM? Why or why not?
Hi everyone, I found some information from someone. Maybe , this can be beneficial for you. Perhaps you're thinking of "non-static whatever cannot be referenced from a static context"? That's the opposite of what you have here. When you're in static context (e.g., inside the body of a static method), you can't refer to any non-static methods or member variables because they don't exist--they require an instance, a this, and there is no this in a static context.