java - For what purpose one would want to create a class's instance inside the same class's main? -
i came across kind of example , had difficulty 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 (); (int = 1; <= 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 kind of implementation - why initiating new class inside same class object , not outside class? there particular reason?
in fact outside
of class object itself. main method
static method, has no dependency on object instance.
you move main method
other java file
. in general work. however, need put static
methods in file. every java file
needs class, may put method in class works for. example, class math
in java pure utility class, has no non-static
method.
however, if create 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 make sense if want value
immutable (not change internal value). so, calling increase()
not increase value creates new instance of object, increased value.
Comments
Post a Comment