开发者

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

开发者 https://www.devze.com 2022-12-10 00:15 出处:网络
Say, I have a code snippet like this: public static void main(String[] args) { new Main().myFunction();

Say, I have a code snippet like this:

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

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


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();


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.


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


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.


new Main().myFunction();

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


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消