سؤال

class Client{
private String name;
private int age;
private int amount;
public Client(Client otherClient){
    name=otherClient.name;
    age=otherClient.age;
    amount=otherClient.amount;
    }
}

What if I want to use this later on:

Client c1=new Client("Smith");

or

Client c1=new Client("Smith",20);

or

Client c1=new Client("Smith",20,100);

How can I have optional parameters? Do I have to define constructors for each case? Thanks

هل كانت مفيدة؟

المحلول 2

First answer is absolutely correct, but if you really want to have only one constructor for all these cases, you can write something like this:

public Client(String name, Integer age, Integer amount) {
    this.name = name;

    if (age != null) {
        this.age = age;
    }

    if (amount != null) {
        this.amount = amount;
    }
}

Usage:

Client c1 = new Client("Smith", null, null);
Client c2 = new Client("Smith", 20, null);
Client c3 = new Client("Smith", null, 100);
Client c4 = new Client(null, 20, 100);
Client c5 = new Client("Smith", 20, 100);

Pay attention that I used wrapper class Integer instead of int in constructor arguments because variable of int type can't be null.


Also, if you make your setters return this, you'll simulate kind of named arguments in Java:

new Client().setName("Smith").setAge(20).setAmount(100)

نصائح أخرى

Yes, you have to overload the constructor, which is something you should read up on. It allows you to provide multiple input parameters for a method. The compiler will choose the appropriate method when the method is called.

Here are the Javadocs on overloading: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top