gpt4 book ai didi

java - 为什么找不到我的子类方法(符号)?

转载 作者:行者123 更新时间:2023-11-29 03:25:21 25 4
gpt4 key购买 nike

我是 Java 的新手,正在编写一个显示继承的简单程序。我在访问派生类中的方法时遇到问题,因为我的变量定义似乎没有使用子类名称,而是使用父类(super class)名称 (Accounts)。为什么调用入金方法会出现找不到符号的错误?

import java.util.*;
import java.text.*;


public class Accounter {

static Scanner input = new Scanner(System.in);
static Accounts myAccount;

public static void main(String[] args) {

int result; //holder for user input
double amount; //holder for desposits and withdrawals

System.out.println("What kind of account would you like to setup?");
System.out.println("Checking[1] or Savings[2]");
result = input.nextInt();

if(result == 1) {
myAccount = new Checking();
} else {
myAccount = new Savings();
}

myAccount.deposit(199.99);



}

}

class Accounts {
double balance;
public String accountName;
public Date dateOpened;
public Date today = new Date();

public Accounts() {
dateOpened = today;
}
public Date getDateOpened() {
return dateOpened;
}
public double getBalance() {
return balance;
}
}

class Checking extends Accounts {
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}
class Savings extends Accounts {
public void deposit(double amount) {
this.balance = this.balance + amount;
}
}

最佳答案

  1. class Accounts 声明为 abstract

  2. 在此类中将double balance声明为protected字段。

  3. 在此类中将public void deposit(double amount)声明为抽象方法。

关于java - 为什么找不到我的子类方法(符号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com