static methods

C

Colin Hemmings

Hi, I'm wondering if anyone can help. I am having trouble understanding
the use of static methods. If I try to compile the following bit of code:

public class square
{
public int squareNum(int number)
{
return (number*number);
}

public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
int square = squareNum(num);
System.out.println(square);
}

}

the compiler complains about the 'squareNum'method not being static. If
I make it static it works fine, but in sme cases I would not be able to
make the method static.

What is the best way to create methods outside of the 'main' method that
are to be called in main? or do Ihave tomake these methods static.

The whole issue why is confusing
 
K

klynn47

Since the main method is static, it can only call static methods in the
class. An instance method has no meaning to the class itself. You have
to have an instance of the class to call an instance method.

You can change the above code to this, and it should work without
making the method static.

int square = new square().squareNum(num);
 
M

Mike Schilling

Since the main method is static, it can only call static methods in the
class. An instance method has no meaning to the class itself. You have
to have an instance of the class to call an instance method.

You can change the above code to this, and it should work without
making the method static.

int square = new square().squareNum(num);

Very true. Note, though, that since the method square() never references
"this", it should be static. This example might be clearer. (Not compiled;
please excuse any typos.)

public class Number
{
private int number;

public Number(int num)
{
number = num;
}

public int square()
{
return number * number;
}

public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
Number n = new Number(num);
System.out.println(n.square());
}
}

In order to call "square", which refers to per-instance fileds, you need to
create an instance of Number.
 
J

James McGill

public class square
{
public int squareNum(int number)
{
return (number*number);
}

public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
int square = squareNum(num);
System.out.println(square);
}

}

the compiler complains about the 'squareNum'method not being static. If
I make it static it works fine, but in sme cases I would not be able to
make the method static.

In this example, which is common, "main" is not a method of any object.
No "Square" object is ever created. Because there's no object in
memory, there's no "squareNum()" method either. It's been declared, but
since it's a regular (volatile) method, it cannot run without an
instance of the class it lives in.

Two ways to work around this.
You could make an instance of Square inside your main method,
and then call squareNum() on that instance you made:

<code>
public class Square
{

public int squareNum(int number)
{
return (number*number);
}

public static void main(String[] args)
{
Square squareInstance = new Square();
int num = Integer.parseInt(args[0]);
int squareValue = squareInstance.squareNum(num);
System.out.println(squareValue);
}
}

</code>

Another way to work it, is to make squareNum() a static method,
and then you can call it directly without making an instance of the
Square object.

public static int squareNum(int number)
//...
int squareValue = Square.squareNum(num);

Of course, if you don't want the exercise, you could just do

int squareValue = (int) Math.pow(num, num);

Notice that Math.pow() is a static method -- it's not necessary to
create a "Math" object in order to call that method.

"main" is confusing, since it's inside the class you want to use, but
you have to understand that it's a static method and that there is no
Object -- and that even if there *was* an Object, main would not know
about it.

You've made a couple of poor choices of identifiers: In Java, it is
suggested that class names start with an upper case letter. That's not
enforced, but it is almost universally followed. But also, you've used
another identifier (int square) for a variable that's within the scope
of a class by the same name (square), which is the sort of thing that
leads to desperate confusion if it goes too far.
What is the best way to create methods outside of the 'main' method that
are to be called in main?

That depends on what you're doing. Usually the most appropriate
approach is to make regular methods, and then create an Object in main,
and call the methods on that object. But there are certainly many
situations where static methods are called for.
Most often, there is data in an object that you want a method to
manipulate, and in order for that to work, you need regular methods, and
an object instance.
The whole issue why is confusing

Static stuff is in the *Class*, and dynamic stuff is in the *Object*.
Once you get your brain around that distinction, it won't be confusing
anymore.
 
J

James McGill

Note, though, that since the method square() never references
"this", it should be static.

Not to argue, but while I can agree with "could be static", I'm not
persuaded to agree that it "should" be static. What's the argument?
Based on performance or what?
 
V

VisionSet

Roedy Green said:
There are two choices. Make them static, OR allocate an object with
new and call its instance methods.

However this shouts loudly that the OP needs to learn some OO.
Learning Java does not teach you OO, in any way, shape or form.
Maybe someone, somewhere can argue successfully that codeing Java in a non
OO way has its uses, but I'd be suprised.

I can only speak for myself but when I started, OO was hard for me, Java was
easy.
But you really do need to get pretty solid with OO for Java to work
properly.
Code maintainabillity is probably the single most important aspect of coding
these days. It's simple, the better your OO the more maintainable your code
will be.
 
V

VisionSet

Very true. Note, though, that since the method square() never references
"this", it should be static. This example might be clearer. (Not compiled;
please excuse any typos.)
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
Number n = new Number(num);
System.out.println(n.square());
}
}

In order to call "square", which refers to per-instance fileds, you need to
create an instance of Number.

System.out.println(new Number(Integer.parseInt(args[0])).square());

And that's an inline version, all I think 'klynn' was proposing.
What has static to do with it?
 
A

Alan Krueger

James said:
Not to argue, but while I can agree with "could be static", I'm not
persuaded to agree that it "should" be static. What's the argument?
Based on performance or what?

First, why require a method to have an object instance when it doesn't
care if it has an instance or not?

Second, non-static methods need to get dispatched to their most derived
implementation, where static methods do not. So, yes, there may be a
performance issue as well.
 
M

Mike Schilling

James McGill said:
Not to argue, but while I can agree with "could be static", I'm not
persuaded to agree that it "should" be static. What's the argument?
Based on performance or what?

Based on the logical structure of the resulting API. If a method's behavior
doesn't depend on an instance, it's confusing to the class's users to make
it an instance method.
 
J

James McGill

Based on the logical structure of the resulting API. If a method's behavior
doesn't depend on an instance, it's confusing to the class's users to make
it an instance method.


So there's no performance consideration or other constraint that would
discourage or encourage the use of static methods in any given scenario?
I had a co-worker who insisted on static methods everywhere. Works
fine, but annoying to use. I like objects, and I like calling methods
on objects. But other than the appeal to my sense of symmetry, I cannot
argue one way or the other.

My instinct tells me that static methods are going to be higher
performance when they can be used, in favor of instance methods where an
anonymous object is created every time the method is called. But I
think that's a degenerate case. Say you've already created your helper
object, is a method call on that object better than the equivalent
static method would be?

Are there other considerations aside from stylistic preference that I
might not be aware of?
 
S

Stefan Ram

James McGill said:
Are there other considerations aside from stylistic preference that I
might not be aware of?

Doctrines to use static methods always or never are both
wrong. I would suggest to follow the J2SE usage:

- use non-static methods for objects that
have a state or could possibly acquire a state
in future version, might it be mutable or immutable,

- use static methods for

- »public static void main«

- mathematical methods, like java.lang.Math.sin, and

- algorithms like java.util.Collections.sort

I do not base my choice on expectations regarding
run-time efficiency.
 
S

Stefan Ram

Doctrines to use static methods always or never are both
wrong. I would suggest to follow the J2SE usage:

But then, static methods can not implement interfaces.
So if a library design is heavily based on interfaces,
this might be a valid reason to avoid static methods
as completely as possible.

For example, one might have

interface Math { double sin( double x ); }
class DefaultMath implements Math { /* ... */ }

or

interface CollectionAlgorithms { void sort( java.util.List l ); }
class DefaultCollectionAlgorithms implements CollectionAlgorithms
{ /* ... */ }
 
M

Mike Schilling

James McGill said:
So there's no performance consideration or other constraint that would
discourage or encourage the use of static methods in any given scenario?

Any such consideration would be the sort of micro-optimization that's almost
never worth worrying about.
 
C

Chris Uppal

[To Colin (the OP): You'll probably find this confusing, if so then just ignore
it totally; it isn't really about your question.]

Mike said:
Note, though, that since the method square() never references
"this", it should be static.

I disagree with this /very/ strongly. I realise that you may be trying to boil
down rather a subtle subject into a relatively simple rule-of-thumb for the OP,
but even so I disagree.

I don't think that statement (taken either literally, or as an approximate
rule-of-thumb) is good guidance. The nearest I could get to it is something
like:

"If the method doesn't refer to 'this', then think about /why/ it
doesn't. Does that mean that the method doesn't belong to
the object at all ? Maybe it should be somewhere else, attached
to a different object perhaps, or even attached to the class."

The key point is /who/ (or what, if you dislike anthropomorphising objects) is
responsible for providing the functionality in question ? In the case in
point, there doesn't seem to be "anyone" who is responsible for computing
squares (it's not an OO program) so I'd make square() static too, but not for
the reason you suggested. If and when the program grows so that it does have
some objects, it would become reasonable to ask whether an individual object (a
Shape perhaps) should have responsibility for arithmetic/geometric
computations. The answer might be yes or no, but the justification for the
answer wouldn't hinge on whether the method(s) in question referred to 'this'.

-- chris
 
E

Ed Kirwan

Chris said:
[To Colin (the OP): You'll probably find this confusing, if so then just ignore
it totally; it isn't really about your question.]

Mike said:
Note, though, that since the method square() never references
"this", it should be static.

I disagree with this /very/ strongly.

I disagree also, but with less passion than those forward-slashes
suggest (I perhaps disagree .very. strongly).

In the general case, a method may not have a, "this," but a subclassed,
overridden method may; and as polymorphism is launched out the window at
the first hint of a, "static," then such subclassing is prohibited. This
is desirable behaviour in some situations, of course, but where desired
it should be made explicit, rather than just defaulting.
 
A

Andrew McDonagh

Chris said:
[To Colin (the OP): You'll probably find this confusing, if so then just ignore
it totally; it isn't really about your question.]

Mike said:
Note, though, that since the method square() never references
"this", it should be static.

I disagree with this /very/ strongly. I realise that you may be trying to boil
down rather a subtle subject into a relatively simple rule-of-thumb for the OP,
but even so I disagree.

I don't think that statement (taken either literally, or as an approximate
rule-of-thumb) is good guidance. The nearest I could get to it is something
like:

"If the method doesn't refer to 'this', then think about /why/ it
doesn't. Does that mean that the method doesn't belong to
the object at all ? Maybe it should be somewhere else, attached
to a different object perhaps, or even attached to the class."

The key point is /who/ (or what, if you dislike anthropomorphising objects) is
responsible for providing the functionality in question ? In the case in
point, there doesn't seem to be "anyone" who is responsible for computing
squares (it's not an OO program) so I'd make square() static too, but not for
the reason you suggested. If and when the program grows so that it does have
some objects, it would become reasonable to ask whether an individual object (a
Shape perhaps) should have responsibility for arithmetic/geometric
computations. The answer might be yes or no, but the justification for the
answer wouldn't hinge on whether the method(s) in question referred to 'this'.

-- chris

At last...someone who sees where the real issue is...!

Well done Chris!
 
T

tom fredriksen

James said:
So there's no performance consideration or other constraint that would
discourage or encourage the use of static methods in any given scenario?
I had a co-worker who insisted on static methods everywhere. Works
fine, but annoying to use. I like objects, and I like calling methods
on objects. But other than the appeal to my sense of symmetry, I cannot
argue one way or the other.

My instinct tells me that static methods are going to be higher
performance when they can be used, in favor of instance methods where an
anonymous object is created every time the method is called. But I
think that's a degenerate case. Say you've already created your helper
object, is a method call on that object better than the equivalent
static method would be?

Are there other considerations aside from stylistic preference that I
might not be aware of?

Its not a matter of style but rather a matter of using the language for
what it was designed for. Java is an OOP language, which means that most
of its power comes from objects and the mechanisms provided therein. If
you want to make all things static then another language is more suited,
such as a procedural language, e.g. C or others.

/tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,185
Members
46,728
Latest member
FernMcmull

Latest Threads

Top