Nimrod
Nimrod

Reputation: 1140

For what purpose one would want to create a class's instance inside the same class's main?

I came across this kind of example and had difficulty to understand it's actuall purpose:

class YieldDemo extends Thread
{
   static boolean finished = false;
   static int sum = 0;
   public static void main (String [] args)
   {
      new YieldDemo ().start ();
      for (int i = 1; i <= 50000; i++)
      {
           sum++;
           if (args.length == 0)
              Thread.yield ();
      }
      finished = true;
   }
   public void run ()
   {
      while (!finished)
         System.out.println ("sum = " + sum);
   }
}

I've never seen this kind of implementation - why initiating a the new class inside the same class object and not outside the class? is there any particular reason?

Upvotes: 2

Views: 63

Answers (1)

Zabuzard
Zabuzard

Reputation: 25903

In fact you are outside of the class object itself. The main method is a static method, thus it has no dependency on any object instance.

You could also move the main method to any other java file. In general it will also work. However, you need to put static methods in some file. As every java file needs to be a class, you may put the method in the class it works for. For example, the class Math in java is a pure utility class, it has no non-static method.

However, if you create something like this:

public final class Value {
    private final int mValue;

    public Value(int value) {
        mValue = value;
    }

    public int getValue() {
        return mValue;
    }

    public Value increase() {
        return new Value(mValue + 1);
    }
}

It can actually make sense if you want Value to be immutable (not change its internal value). So, calling increase() does not increase the value itself but creates a new instance of this object, with an increased value.

Upvotes: 1

Related Questions