Re: Non static method error explanation?
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Wed, 4 Mar 2009 14:37:58 -0800 (PST)
On Mar 4, 4:51 pm, Eric Sosman <Eric.Sos...@xxxxxxx> wrote:
Joshua Cranmer wrote:
Salad wrote:
I guess there's one last question I have...what would a typical Java
programmer use...use/add the keyword "static" in the calledRoutine
line or create an instance? I guess coming from the world of
structured programming I wasn't thinking objects, I was thinking
recursion in using keyword "new" in this example.
In this specific example, I would probably go with just a simple static
method.
I would say that most static methods fall under one of two categories:
some sort of factory mechanism for creating objects, or a method in a
class acting as a namespace (the methods in java.lang.Math or
java.util.Collections are examples of these).
There is a third category which I would say exists: utility methods for
small, "toy" programs.
I've also found them convenient for doing argument validation
and conversion and similar things that can be inconvenient in a
constructor. For example, this won't work:
class Terrier extends Dog {
Terrier(int kgWeight) {
if (kgWeight > 100)
throw new IllegalArgumentException(
"no terrier could possibly be that big");
super(kgWeight);
}
}
... but this would:
class Terrier extends Dog {
Terrier(int kgWeight) {
super(checkWeight(kgWeight));
}
private static int checkWeight(int kgWeight) {
if (kgWeight > 100)
throw new IllegalArgumentException(
"no terrier could possibly be that big");
return kgWeight;
}
}
Note that 'checkWeight()' in this example can be a 'final' instance
method without harm.
My personal preference would be to do just that. It should be 'final'
because it's invoked from the constructor. It should be an instance
method, even though it doesn't interact with 'this' or instance state,
because it is used in an instance context. It doesn't hurt to make it
an instance method because there aren't separate copies of the method
for different instances. Because the method is relevant to instance
instantiation, I prefer that it not be static.
--
Lew
.
- Follow-Ups:
- Re: Non static method error explanation?
- From: Joshua Cranmer
- Re: Non static method error explanation?
- References:
- Non static method error explanation?
- From: Salad
- Re: Non static method error explanation?
- From: Eric Sosman
- Re: Non static method error explanation?
- From: Salad
- Re: Non static method error explanation?
- From: Joshua Cranmer
- Re: Non static method error explanation?
- From: Eric Sosman
- Non static method error explanation?
- Prev by Date: Re: Non static method error explanation?
- Next by Date: Re: Non static method error explanation?
- Previous by thread: Re: Non static method error explanation?
- Next by thread: Re: Non static method error explanation?
- Index(es):
Relevant Pages
|