Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object control while creating a new one with constructor

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;
     }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You got some hints in the comments, but I’ll post my answer here. This is only a suggested way of doing it, but there could be other approaches, depending on how you want to design your code.

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading