哪个更好或者哪个是正确的方法,你能否也给出解释(我不知道在谷歌上使用什么搜索词)。
第一种方式:
Public Class A()
{
Paint _paint _test;
public void running()
{
_test = new Paint();
//use paint
}
}
或
Public Class B()
{
Paint _paint _test = new Paint();
public void running()
{
//use paint
}
}
谢谢
最佳答案
当您可能(也许在将来)可能想要将参数传递给成员的构造函数时,第一种方法更好,例如:
class Foo{
private Bar bar;
public Foo(){
bar = new Bar();
}
public Foo( String s ){
bar = new Bar( s );
}
}
当您知道永远不想将参数传递给成员的构造函数并且您有多个构造函数都需要初始化该成员时,第二种方法更好,例如:
class Foo {
private Bar bar = new Bar();
public Foo( String s ){ ... }
public Foo( int i ){ ... }
public Foo( double d ){ ... }
public Foo( String s, int i ){ ... }
}
关于java - 将变量初始化为类或构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10340863/