[英]Object control while creating a new one with constructor
I have a simple bank account class.我有一个简单的银行账户 class。 I don't want to create an object if the user's age is younger than 18.如果用户的年龄小于 18 岁,我不想创建 object。
So I tried to create a class like this.所以我试着像这样创建一个 class 。 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;
}
}
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:您可以使用 static 工厂方法,仅当年龄大于或等于 18 岁时才会创建 object。示例:
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:您将创建您的 BankAccount 为:
// 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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.