构造函数中有很多参数 [英] Having lots of parameters in a constructor

查看:189
本文介绍了构造函数中有很多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在构造函数中有很多参数是错误的吗?喜欢10到15个参数吗?因为我正在设计一个类,其中构造函数将具有许多参数,例如Person类.

Is it wrong to have a lot of parameters inside a constructor? Like 10 to 15 parameters? Because I was designing a class where a constructor will have lots of parameters, for example, a Person class.

我的示例人员类的构造函数中有6个参数:

My example person class has 6 parameters in its constructor:

public class Person {
    private String fName;
    private String lName;
    private String mInitial;
    private int age;
    private String contactNumber;
    private String emailAddress;

    public Person(String fName, String lName, String mInitial, int age, String contactNumber, String emailAddress) {
       //insert rest of code here 
    }
}

那是错的吗?为构造函数创建很多参数?

Is that wrong? Creating lots of parameters for a constructor?

然后我打算创建一个名为Employee的类,然后将其扩展到person类,然后它也将具有一个长的构造函数.

Then I am planning to create a class named Employee, then extending it to person class, then it will have a long constructor as well.

让我担心的是实践,这是好事还是什么?还有其他建议吗?

The thing that worries me about is the practice, is this good or what? Any other suggestions?

推荐答案

  1. 通常,如果您发现自己的参数太多,则意味着您没有足够的低级类.在您的情况下,您可能有一个class Name { /* fname, lname, initial, */ },也许还有一个class Contact { /* email, phone */ }

扩展类时,让构造函数将基数作为一个参数,然后添加新的额外参数. (您可能表示Employee会扩展Person,而不是反过来,所以public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }

When you extend your class, have the constructor take the base as one parameter, and then add the new extra parameters. (You probably mean Employee will extend Person, rather than vice versa, so public Employee (Person person, Company company, String employeeId) { super(person); this.company = company; this.employeeId = employeeId; }

好问题!

这篇关于构造函数中有很多参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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