类中的构造函数不能应用于给定的类型;

时间:2014-11-10 14:24:58

标签: java constructor

我有两个类,称为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);
    }

3 个答案:

答案 0 :(得分:0)

您应该使用Transactions构造函数的相同参数在Customer类中定义构造函数,或者应该向Customer类添加无参数构造函数。

当一个类没有任何构造函数时(因为你的Transactions类没有),编译器会生成一个没有参数的默认构造函数。此构造函数调用超类的无参数构造函数。如果超类没有无参数构造函数(不是为Customer类生成的,因为它已经有了不同的构造函数),你的代码将无法编译。

答案 1 :(得分:0)

您尚未为类Transactions

定义构造函数

它调用了不存在的超类的隐式构造函数,因为你定义了自己的构造函数

答案 2 :(得分:0)

你破坏了继承/封装机制。

  1. 在Java类中,所有成员必须是“私有”。
  2. 如果您希望子类可以访问某些成员,则必须将这些成员声明为“protected”。
  3. 在子类中,必须声明一个应该通过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;
         }
    }