简体   繁体   中英

Method was invoked without being called

As you can see, the m1() method was not called in the main method but it prints the statement. I just want to know how the execution happened without invoking the m1() method.

class Test
{
    double a=m1();
    double m1()
    {
        System.out.println("m1() instance method invoked");
        return 100;
        

    }
    public static void main(String[] args)
    {
        Test t=new Test();
    }
}

Test 's member a is initialized with a call to m1() . When you create an instance of Test (by calling new Test() ), its members get initialized, and m1 gets called.

double a=m1();

This is inline initialization.

we have multiple type of initialization in java like inline,static block,non-static block,constructor: Initializing Fields Oracle Docs

You're right. you have not invoked m1() directly but after creating a new instance of Test , its members get initialized. how?

java will search for inline initialization or non-static block initialization or constructor initialization.

in your code, you just have inline initialization. so java will evaluate m1() (invoke m1() ) and will assign its value to your instance member a . so actually You have invoked m1() but indirectly.

in java programming language everything starts from main function, so when you creat an instance from Test, the fields of this class are loaded and inline initialize and default constructor is called. so that's why your m1 function is called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM