Home > Software engineering >  Object control while creating a new one with constructor
Object control while creating a new one with constructor

Time:12-09

I have a simple bank account class. I don't want to create an object if the user's age is younger than 18.

So I tried to create a class like this. But It doesn't work. Can I do something like what I want in Object-Oriented programming?

public class BankAccount {

    private String name;
    private String id;
    private  int age;
    private  double balance;
    private String accNumber;

    public BankAccount(String name, String id, int age, double balance, String accNumber) {
        this.name = name;
        this.id = id;
        this.balance = balance;
        this.accNumber = accNumber;
        if (age<18){
            System.out.println("You can not create a bank account If You're younger than 18 years old");
            return;
     }
}

CodePudding user response:

You got some hints in the comments, but I'll post my answer here, as a suggested approach. You could use a static factory method that will create your object only if the age is greater than or equal to 18. Example:

public class BankAccount {

    private String name;
    private String id;
    private int age;
    private double balance;
    private String accNumber;

    // Notice the private constructor. This class can be instantiated only by call the static method #from
    private BankAccount(String name, String id, int age, double balance, String accNumber) {
        this.name = name;
        this.id = id;
        this.age = age;
        this.balance = balance;
        this.accNumber = accNumber;
    }

    public static BankAccount from(String name, String id, int age, double balance, String accNumber) {
        if (age < 18) {
            return null;
        }

        return new BankAccount(name, id, age, balance, accNumber);
    }

}

And you would create your BankAccount as:

// This will be null, because age < 18
BankAccount bankAccount = BankAccount.from("name", "id", 1, 0, "accNumber");

// This will be an actual object
BankAccount bankAccount = BankAccount.from("name", "id", 20, 0, "accNumber");
  • Related