Saobi
Saobi

Reputation: 17021

What does it mean to call a Java method using "new" in a statement?

Say, I have a code snippet like this:

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

Where myFunction is another method (could be non-static) defined in the same class as Main. Why would you do the above? Why not just do: myFunction();

Upvotes: 1

Views: 6402

Answers (6)

OscarRyz
OscarRyz

Reputation: 199225

What does it mean to call a Java method using “new” in a statement?

It creates a new instance of the given class

Why not just do: myFunction();

Most likely myFunction() is an instance method:

public void myFunction() { 
    ....
}

In order to invoke an instance method, you need an instance first.

Using the new keyword creates a new object and then it invokes the myFunction method on that object.

Methods marked with the static access modifier are class methods, they belong to the whole class and don't need an instance to work.

Methods who are not marked as static do need an instance to work.

That's what the compiler error:

...cannot invoke a non-static method from a static context...1

is all about.

1or something like that

Upvotes: 1

Andrew Keith
Andrew Keith

Reputation: 7563

its because myFunction() is non static, so you need an instance of the class Main to call it.

new Main().myFunction();

can be broken down into

new Main() // instantiate first, then only .myFunction()

Upvotes: 0

user120587
user120587

Reputation:

Most likely myFunction is a instance method and not a class (static) method, therefore must be called on an instance of the class. Since you are inside a static method, you can not directly call instance methods, you must create an instance first which is what new Main() does, then you can call it.

Upvotes: 1

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

myFunction is an instance method that belongs to the type Main. What your code does is that it first creates a new instance of type Main (i.e. new Main()) and then invokes the method myFunction on that instance.

A more verbose version of your code would be:

Main mainObj = new Main();
mainObj.myFunction();

Upvotes: 5

Stephen C
Stephen C

Reputation: 718826

new Main().myFunction();

This creates a new instance of the Main class and then invokes the myFunction() method on it.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124642

Well, "Main" is a class, and 'main' is a method, so they are not the same thing. If you wanted to create a new instance of the "Main" class and call the myFunction method you would do as your example shows. Now, if "main" is a method of "Main"... then I can't say why you would actually do such a thing.

Upvotes: 0

Related Questions