2013-02-20 122 views
2

我把下面的构造函数放在一起。我有一个问题:我如何在没有参数的情况下使用相同的构造函数,并且同时使用两个或三个构造函数?有多种方法可以做到这一点吗?谢谢构造函数中的多个参数

public class bankaccount { 

    String firstnameString; 
    String lastnameString; 
    int accountnumber; 
    double accountbalance;; 

    public bankaccount(String firstname,String lastname){ 
    int accountnumber=999999; 
    double accountbalance=0.0; 
    } 
} 
+0

只需定义多个构造函数。 – 2013-02-20 15:08:11

+1

您正在当前构造函数中声明局部变量,而您可能想要设置字段的值。你必须解决这个问题...... – jlordo 2013-02-20 15:21:50

+0

@jlordo他也不使用'firstname'或'lastname' – 2013-02-20 15:22:42

回答

6

您需要实现所有想要使用的变体。然后,您可以使用this()构造函数之间的调用,避免代码冗余:

public class BankAccount { 

    public BankAccount(){ 
    this("", ""); 
    // or this(null, null); 
    } 

    public BankAccount(String firstname){ 
    this(firstname, ""); 
    // or this(firstname, null); 
    } 

    public BankAccount(String firstname, String lastname){ 
     // implement the actual code here 
    } 
} 

顺便说一句,你应该看看Java Coding Conventions - class names(因此构造函数)骆驼情况下注意。

+0

风格点 - 我会建议'空'将是一个更合适的默认值。但每一个都是他们自己的... – 2013-02-20 15:11:11

+0

@DuncanJones同意,我的头脑在这些替代品之间疯狂跳跃,同时打字:)最后,它基本上取决于“最终”构造函数的作用 – 2013-02-20 15:20:56

0

如果您没有实现任何构造函数,则会为您提供无参数构造函数。如果你想拥有多个构造函数,你可以自己实现所有的构造函数。

public class bankaccount { 

    String firstnameString; 
    String lastnameString; 
    int accountnumber; 
    double accountbalance;; 

    public bankaccount(String firstname,String lastname){ 
    int accountnumber=999999; 
    double accountbalance=0.0; 
    } 

    public bankaccount(){ 
    // put code here, or call this(null,null)/a different constructor 
    } 

} 
+0

这两个构造函数都具有相同的效果。 – jlordo 2013-02-20 15:20:18

0

其他人建议你创建多个构造函数,这很好。但是,在某些情况下,您可能更喜欢只有零参数构造函数,并使用getter和setter来访问属性。

您的BankAccount类可能是这些情况之一。它看起来像一个数据对象,它是通过使用某些ORM(例如Hibernate)持久化到DBMS中的对象之一。 Hibernate不需要多参数构造函数,它将调用零参数构造函数并通过getters和setter访问属性。

这是什么课程?它是映射到对象的数据库实体吗?你真的需要所有这些构造函数吗(这可能是浪费时间)?

从理论上讲,我的建议可以被认为是与OO设计的良好实践的斗争,但实践与理论有些不同。如果你的类只是携带一些数据,你的构造函数不对所提供的参数的有效性进行检查,那么你可以列出属性并使用IDE的功能来创建getter和setter。