Re: static methods




<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.


.



Relevant Pages

  • Re: random number generator help
    ... You are calling an instance method from a static method. ... It will work if you add the keyword "static" to the instance method: ... private static int RandomNumber ... Random random = new Random; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: MethodType in python 2.2
    ... cannot create 'instance method' instances ... In 2.2, *some* type objects, like int, were turned into callable ... contructors as part of the introduction of new-type classes. ... When the experiment proved to be a success, additional type objects were ...
    (comp.lang.python)