Re: static methods
- From: "Mike Schilling" <mscottschilling@xxxxxxxxxxx>
- Date: Sat, 04 Mar 2006 17:37:10 GMT
<klynn47@xxxxxxxxxxx> wrote in message
news:1141493354.561120.127100@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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.
.
- Follow-Ups:
- Re: static methods
- From: Chris Uppal
- Re: static methods
- From: VisionSet
- Re: static methods
- From: James McGill
- Re: static methods
- References:
- static methods
- From: Colin Hemmings
- Re: static methods
- From: klynn47
- static methods
- Prev by Date: Re: static methods
- Next by Date: NIO versus NET?
- Previous by thread: Re: static methods
- Next by thread: Re: static methods
- Index(es):
Relevant Pages
|