How does the new Java operator work?

Asked

Viewed 425 times

-2

I don’t understand how new works below:

public Main(){
   System.out.println("");
}


public static void main(String[] args){
   new Main();
}
  • 2

    What should be public Main()?

1 answer

4


Well, that code could be posted completely to give you a better idea of what you’re doing, but you can understand even with that part.

This is a code that doesn’t make much sense under normal conditions, but it can explain what happens.

The code should be about this:

public class Main {
    public Main() { System.out.println(""); }

    public static void main(String[] args) { new Main(); }
}

So we have a class called Main which has a constructor of the same name. How do I know you have a constructor? Well, the constructor has no return type, the syntax indicates this. And do I know the class name without it being in question? The builder has the same class name always, so he is a class builder Main.

If you want to understand better about builders you can read What good is a builder?. You’ll find that this constructor makes little sense in real code. In fact almost "everything" you want to know about programming can search here and have good answers, at least the most voted. Do this.

When you create a class you can create objects from it. See more in What is the difference between a class and an object?. In Java to create an object from a class you call the constructor you created or a pattern that the compiler creates for you in certain circumstances.

And to call the constructor you have to say that you will create a new object requiring the use of the reserved word new before the call of the constructor, not to be confused with a call of a simple normal method.

So you’re creating an object like Main and calling your builder by writing nothing on the screen, which is what’s inside the builder.

As it is not storing in a variable the object is lost soon after the construction is carried out. What is ok in this code, it doesn’t do anything useful at all, but in some cases you might want to put in a variable.

Such a stateless code, in general does not need a class, an instance, the method could be static and just call it, something like that:

public class Main {
    public static void Main() { System.out.println(""); }

    public static void main(String[] args) { Main(); }
}

Or I could do something simpler and more meaningful.

The other method is something standard language used as an application entry point. See more in Why it is mandatory to implement "public Static void main (String [] args)"?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.