方法被调用而未被调用。

huangapple go评论80阅读模式
英文:

Method was invoked without being called

问题

正如你所看到的,m1() 方法没有在主方法中被调用,但它却打印了语句。我只想知道在没有调用 m1() 方法的情况下是如何发生执行的。

class Test
{
    double a = m1();
    double m1()
    {
        System.out.println("m1() 实例方法被调用");
        return 100;
    }
    public static void main(String[] args)
    {
        Test t = new Test();
    }
}
英文:

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

答案1

得分: 3

Test的成员a通过调用m1()进行初始化。当你创建一个Test的实例(通过调用new Test()),它的成员被初始化,并且会调用m1

英文:

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.

答案2

得分: 2

double a = m1();

这是内联初始化。

在Java中,我们有多种类型的初始化,如内联初始化、静态块初始化、非静态块初始化、构造函数初始化:**[Initializing Fields Oracle Docs][1]**

你是对的。虽然你没有直接调用`m1()`,但在创建了`Test`的新实例之后,它的成员就被初始化了。是通过什么方式呢?

Java会查找内联初始化、非静态块初始化或构造函数初始化。

在你的代码中,只进行了内联初始化。因此Java会评估`m1()`(调用`m1()`),并将其值赋给你的实例成员`a`。所以实际上你已经间接地调用了`m1()`。


  [1]: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
英文:
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.

答案3

得分: 1

在Java编程语言中,一切都始于主函数(main function)。因此,当您从Test类创建一个实例时,该类的字段将被加载并进行内联初始化,并调用默认构造函数。这就是为什么您的m1函数会被调用。

英文:

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

huangapple
  • 本文由 发表于 2020年9月20日 11:01:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63975131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定