最好是在变量上调用方法或将其链接到构造函数? [英] Is it better to call a method on a variable or chain it to the constructor?

查看:69
本文介绍了最好是在变量上调用方法或将其链接到构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何类上都有调用此类方法的示例.

There are examples of calling such methods on any class.

即:

SampleClass sc=new SampleClass();
sc.someMethod();

还是最好使用

new SampleClass().someMethod();

请详细解释.

推荐答案

两个选项都一样,但是第一个选项更好...

Both options are as good, but first one is better...

如果您使用

SampleClass sc=new SampleClass();
sc.someMethod();

您可以使用类的相同对象来调用该类的其他方法.

You can call other methods of this class using same object of class.

如果您使用

new SampleClass().someMethod();

您需要另一个对象来调用此类的其他方法.

You require another object to call other method of this class.

其他示例是

loop { // Here loop can be any type, for/while/do-while
    new SampleClass().someMethod();
}

这将创建循环执行多次的相同类的对象.但是,如果您选择第一个选项

this will create objects of same class as many times your loop execute. But if you go with first option

SampleClass sc=new SampleClass();
loop { // Here loop can be any type, for/while/do-while
    sc.someMethod();
}

这不会导致创建许多对象来调用方法.

This will not cause to create many objects to call method.

但是,是的,如果您只需要调用一个方法而又没有进入循环,则可以使用new SampleClass().someMethod();

But Yes, if your need is to call only one method and that is not into loop, you can go with new SampleClass().someMethod();

这篇关于最好是在变量上调用方法或将其链接到构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆