How does the class referenced by itself work?

Let's say we have a class like this:

class XCopy {
    public static void main(String[] args) {
        int orig = 42;
        XCopy x = new XCopy();
        int y = x.go(orig);
        System.out.println(orig + " " + " y);
    }
}

I know the method is gomissing, but it doesn't matter. Should this work? It seems like this, but I just can't imagine how this self-promotion inside the class works; Does it have any side effects? Why does this work? Isn't this some kind of infinite recursive loop?

Anyway, I just can't figure out how this works; thanks in advance.

+3
source share
6 answers

Causing

XCopy x = new XCopy();

you are actually calling an empty XCopy constructor, not the main method.

So the calls look like this:

JVM calls XCopy.main();
main method creates new instance of XCopy by calling XCopy empty constructor
XCopy constructor ends
main method ends -> program ends
+3
source

I understand that you look at it and think that this is a problem with the chicken and the egg, but it is not at all.

OO, , , Java. Java , " ". (String []) . . - , , " " "". .

Java (.. ) , , . . , / . Math, . - , OO, /, OO.

. , .

Java ALWAYS, - ( , ).

, , JVM . . . main .

, (String []), :

XCopy x = new XCopy();

XCopy, ( ) x . XCopy , .

, , , !

:

Namespace XCopy 
{
  function void main(String[]) 
  { 
    int orig = 42;
    XCopy x = new XCopy();
    int y = x.go(orig);
    System.out.println(orig + " " + " y);
  }
}

Class XCopy
{
   method int go(int i) 
   {
      ....
      return whatever;
   }
}

, , , .

, !

+3

? main() , . , .

, , makeCopy(); .

, "" / - ; - this.

+1

- , , , Xcopy. , . , , .

+1

main() , , . + JVM . , main(), .

+1

:

public class Person {
  private String name;
  private Person favorite;
  public Person(String name) { setName(name); }
  public void setFavorite(Person favorite) {this.favorite = favorite;}
  public Person getFavorite() { return favorite; }
  public void setName(String name) {this.name = name;}
  public String getName() { return name; }
  public static void main(String args[]) {
    Person a = new Person("Alex");
    Person b = new Person("Becky");
    Person c = new Person("Chris");
    Person d = new Person("David");
    a.setFavorite(b);
    b.setFavorite(c);
    c.setFavorite(c);
  }
}

, - . . - ; - . . , .

- , , ? . . .

Until you take a step by saying, “I am going to ask each person who their loved one is. Then I am going to ask the person who their favorite person is. Stopping until I find David. Because then you have a chance go in cycles forever.

+1
source

All Articles