我创建了一个名为bank的类及其子类ATM,我希望声明一个子类ATM的实例。当我如下所示声明它时,它会给我一个错误。
package bank;
import java.util.Scanner;
public class Bank {// Bank class
protected int PIN,chequing_balance,savings_balance;
public void set_PIN(int PIN){
this.PIN= PIN;
}
public int get_PIN(){
return this.PIN;
}
public void set_chequing_balance(int chequing_balance){
this.chequing_balance=chequing_balance;
}
public int get_chequing_balance(){
return chequing_balance;
}
public void set_savings_balance(int savings_balance){
this.savings_balance=savings_balance;
}
public int get_savings_balance(){
return savings_balance;
}
public class ATM extends Bank{// ATM is a subclass of Bank
private void ATM(){
PIN=1207605;
chequing_balance=0;
savings_balance=0;
}
public void deposit_savings(int amount){
this.savings_balance+=amount;
}
public void withdrawl_savings(int amount){
this.savings_balance-=amount;
}
public void transfer_savings_to_chequing(int amount){
this.chequing_balance+=amount;
this.savings_balance-=amount;
}
public void deposit_chequing(int amount){
this.chequing_balance+=amount;
}
public void withdrawl_chequing(int amount){
this.chequing_balance-=amount;
}
public void transfer_chequing_to_savings(int amount){
this.savings_balance+=amount;
this.chequing_balance-=amount;
}
}
public static void main(String[] args) {
int key,amount;
ATM x= new ATM(); // declaration of instance of ATM subclass
Scanner input= new Scanner(System.in);
do{
System.out.println("Please enter transaction type 1.Deposit, 2. Withdraw 3. Transfer ");
key=input.nextInt();
}while(key<1||key>3);
do{
System.out.println("Please enter desired amount");
amount=input.nextInt();
}while(amount<0);
if (key==1)
{
System.out.println("Please enter account desired 1. Chequing 2. Savings");
key=input.nextInt();
if (key==1)
{
x.deposit_chequing(amount);
}
else if(key==2)
{
x.deposit_savings(amount);
}
}
else if (key==2)
{
System.out.println("Please enter account desired 1. Chequing 2. Savings");
key=input.nextInt();
if(key==1)
{
x.deposit_chequing(amount);
}
else if(key==2)
{
x.deposit_savings(amount);
}
}
else if(key==3)
{
System.out.println("Please enter type of transaction you want 1. Chequing to Savings 2. Savings to Chequing");
key=input.nextInt();
if (key==1)
{
x.transfer_chequing_to_savings(amount);
}
else if (key==2)
{
x.transfer_savings_to_chequing(amount);
}
}
}
}
答案 0 :(得分:2)
private void ATM(){
这是私有的,甚至不是构造函数,它是一种方法。构造函数不应该有返回类型。
此外,ATM不应扩展银行。
答案 1 :(得分:0)
您的构造函数不应该声明它应该是的返回类型:
public ATM() {
....
}
当你有一个子类时,你必须让它通过IS-A测试。所有子类都应对此测试说“是”,以便成为适当的子类。 ATM IS-A银行?嗯,不完全是。你可以为ATM提出一个超类,但银行可能不是它。银行可能拥有许多ATM。 ATM IS-A AccountAccessPoint或IS-A CashDispenser。但这更像是一种建模练习。