Reputation: 21
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();
}
}
Upvotes: 1
Views: 645
Reputation: 444
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.
Upvotes: 2
Reputation: 311163
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.
Upvotes: 3
Reputation: 13
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
Upvotes: 1