> i don't know whether this is the proper place to raise the following
> question,if u think it's the wrong place to do so ,please delete this
> post
>
> i was told that within the static method , i can only use the static
> methods or static variables,
You were given bad advice, in that the language used was imprecise.
You can not call instance methods from a static context.
But the contents of a static method are not necessarilly all static context.
For example in your main() method 'a' is not a static context, so when you
call methods on it you are not using a static context.
> but i found that the following codes are
> legal:
[quoted text clipped - 12 lines]
> it seems that a.print() and new abc() are not static methods ,why??
> thank you very much for your attention and help.
abc() is not a method it is a constructor and can be called from a static
conext, essentially it must be called from a context that is not the
instance it is creating ;-)
print() is being called on an instance of abc (ie a) as it must be.
--
Mike W
gencko - 23 Mar 2006 14:28 GMT
thanks a lot.
But i still got a little bit confused,so can u give me an example to
show the wrong usage of statics?i mean what will the codes be like if
we tried to call instance methods in static context ,there are piles of
'good' codes and short passages about statics in the textbooks that i
read,so i really wanna what the 'bad' codes are like
thank you very much for another time
VisionSet - 23 Mar 2006 18:26 GMT
> thanks a lot.
>
[quoted text clipped - 5 lines]
>
> thank you very much for another time
Well it isn't so much bad, as impossible. The compiler won't let you do it
and it doesn't make any sense.
eg
class MyClass {
public void methA() {}
public static void main(String[] args) {
methA(); // illegal, you need an instance
// of MyClass to call an instance method
new MyClass().methA(); // legal, we have an instance.
}
}
on the other side of the coin it is legal to call a static method from an
instance, but it is bad practice, since it is misleading.
class MyClass {
public static void methB() {}
public static void main(String[] args) {
methB(); // legal, MyClass is implicit
MyClass.methB(); // explict version
MyClass inst = new MyClass();
inst.methB(); // legal, but bad. [1]
}
}
[1] This is legal because the compiler says, I know that 'inst' is an
instance of MyClass so I know how to call the static method. But it is
*bad* because it looks like you are calling an instance method, so is
misleading to the maintainer. Obviously it is also a waste of resources
instantiating the object, but the usual times people do this is when they
have the instance anyway.
--
Mike W
gencko - 24 Mar 2006 05:21 GMT
thanks ,i think i've got clear about this problem,really thanks a lot
gencko - 24 Mar 2006 05:21 GMT
thanks ,i think i've got clear about this problem,really thanks a lot