我的程序中的构造函数遇到了一些问题。它是一个存储客户数据的简单银行数据库。我必须实施在两个账户之间存入,提取和转移现金的方法。我已经实现了这种构造函数来添加新的银行帐户:
public Customer() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter id of customer:");
this.id = scan.nextLine();
File folder = new File("CustomerDataBase" + File.separator + this.id + ".txt");
if(folder.exists()) {
System.out.println("Customer ID already exists!");
System.exit(1);
}
try {
System.out.println("Enter name of customer:");
this.name = scan.nextLine();
System.out.println("Enter surname of customer:");
this.surname = scan.nextLine();
System.out.println("Enter PESEL number of customer:");
this.pesel = scan.nextLine();
System.out.println("Enter address of customer:");
System.out.println(" Street:");
this.adressStreet = scan.nextLine();
System.out.println(" City:");
this.adressCity = scan.nextLine();
System.out.println(" Zip Code: ");
this.zipCode = scan.nextLine();
System.out.println("Enter funds of Customer:");
this.funds = Double.parseDouble(scan.nextLine());
this.saveCustomer();
scan.close();
}catch(NumberFormatException e) {
System.out.println("Error : " + e);
System.exit(1);
}
}
然后我有一个方法withdraw
:
static void withdraw (int amount, int id) {
File f = new File("CustomerDataBase" + File.separator + String.valueOf(id) + ".txt");
Scanner fRead;
Customer tempCustomer = new Customer();
try{
fRead = new Scanner(f);
tempCustomer.id = fRead.nextLine();
tempCustomer.name = fRead.nextLine();
tempCustomer.surname = fRead.nextLine();
tempCustomer.pesel = fRead.nextLine();
tempCustomer.adressStreet = fRead.nextLine();
tempCustomer.adressCity = fRead.nextLine();
tempCustomer.zipCode = fRead.nextLine();
tempCustomer.funds = Double.parseDouble(fRead.nextLine()) - id;
fRead.close();
tempCustomer.saveCustomer();
}catch(FileNotFoundException e) {
System.out.println("File not found!");
System.exit(1);
}
}
withdraw
方法从文件中读取数据,并且必须将其存储在类中。所以我将对象创建为客户类型。但我想只使用" plain" (默认)Java在您未声明自己的时提供的构造函数。
怎么做?我读到了super():
语句,但如果我理解正确,它只有在你从另一个类继承时才有用。
答案 0 :(得分:0)
每个类都带有一个在类本身中不可见的默认构造函数。 但是,请注意,如果指定默认构造函数以外的构造函数,则不能使用默认构造函数,请参阅下面的@Rustam注释。例如,假设您的Customer类如下所示:
public class Customer {
private String name;
private String lastName;
private age int;
private String ssn;
//default constructor that is NOT visible
Customer()
{
}
//other constructor given name and lastName
Customer(name, lastName)
{
this.name = name;
this.lastName = lastName;
}
//getters and setters
}
默认情况下会创建构造函数Customer(),您无需在类中包含它。
然后,您可以使用默认构造函数创建客户实例,然后您需要使用setter来设置属性,如下所示:
public class Test {
public static void main(String [] args){
Customer c = new Customer();
//setting parameters
c.setName("Jose");
c.setLastName("Mejia");
}
}