Re: how to use static methods
- From: "VisionSet" <spam@xxxxxxxxxxxx>
- Date: Thu, 23 Mar 2006 17:26:39 GMT
"gencko" <passageliu@xxxxxxxxx> wrote in message
news:1143120490.075042.96430@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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
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
.
- Follow-Ups:
- Re: how to use static methods
- From: gencko
- Re: how to use static methods
- From: gencko
- Re: how to use static methods
- References:
- how to use static methods
- From: gencko
- Re: how to use static methods
- From: VisionSet
- Re: how to use static methods
- From: gencko
- how to use static methods
- Prev by Date: Re: how to make java application executable (exe)
- Next by Date: Re: How java handle GUI updates
- Previous by thread: Re: how to use static methods
- Next by thread: Re: how to use static methods
- Index(es):
Relevant Pages
|