我有两个类,称为Customer和Transactions。 在尝试在Transactions中扩展Customer时,我收到错误。有人可以帮忙吗? 这是我的代码
public class Customer{
public String name;
public String surname;
public int id;
public int ban;
public double balance;
public Customer(String pName, String pSurname, int pId, int pBan, double pBalance)
{
name = pName;
surname = pSurname;
id = pId;
ban = pBan;
balance = pBalance;
}
}
public class Transactions extends Customer{
public double Deposit(){
double deposit = Double.parseDouble(JOptionPane.showInputDialog("How much would you like to deposit?"));
balance = balance + deposit;
JOptionPane.showMessageDialog(null,"Transaction complete. Your new balance is " + balance,"Transaction Complete", JOptionPane.PLAIN_MESSAGE);
return balance;
}
public double Withdraw(){
double withdraw = Double.parseDouble(JOptionPane.showInputDialog("How much would you like to withdraw?"));
if(balance >= withdraw){
balance = balance - withdraw;
JOptionPane.showMessageDialog(null,"Transaction complete. Your new balance is " + balance,"Transaction Complete", JOptionPane.PLAIN_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null,"Error. You were trying to withdraw more than you have in your account.","ERROR", JOptionPane.ERROR_MESSAGE);
}
return balance;
}
public void checkBalance(){
JOptionPane.showMessageDialog(null, "Name: " + name + " " + surname + "\nID: " + id + "\nBAN: " + ban + "\nBalance: " + balance);
}
答案 0 :(得分:0)
您应该使用Transactions
构造函数的相同参数在Customer
类中定义构造函数,或者应该向Customer
类添加无参数构造函数。
当一个类没有任何构造函数时(因为你的Transactions
类没有),编译器会生成一个没有参数的默认构造函数。此构造函数调用超类的无参数构造函数。如果超类没有无参数构造函数(不是为Customer
类生成的,因为它已经有了不同的构造函数),你的代码将无法编译。
答案 1 :(得分:0)
您尚未为类Transactions
它调用了不存在的超类的隐式构造函数,因为你定义了自己的构造函数
答案 2 :(得分:0)
你破坏了继承/封装机制。
在子类中,必须声明一个应该通过super关键字调用超类构造函数的构造函数。请查看以下示例。
public class Person {
protected String name;
protected String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
}
}
public class Student extends Person {
private String Level;
public Student(String name, String age, String level){
super(name, age);
this.level = level;
}
}