如何从父级实例调用子类方法?

发布于 2025-01-27 13:14:09 字数 2760 浏览 1 评论 0 原文

public class Account {
    double currentBalance;
    
    Account(double currentBalance) {
        this.currentBalance = currentBalance; 
    }
    
    double getBalance() {
        return(this.currentBalance);
    }
    
     void deposit(double amount) {
        this.currentBalance += amount;
    }

    void withdraw(double amount) {
        this.currentBalance -= amount;
    }
    
    public String toString() {
        return("Your current account balance is: $" + this.currentBalance);
    }
}
 public class SavingsAccount extends Account {
    double interestRate;

    SavingsAccount(double interestRate, double amount) {
        super(amount);
        this.interestRate = interestRate;
    }

    void addInterest(double interestRate) {
        this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
    }
    
    public String toString() {
        return("Your current account balance is: $" + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
    }
}
public class AccountTester {
    public static void main(String[] args) {
        System.out.println("Welcome to the COMP 251 BANK");
        
        Account[] acc = new Account[10];

        acc[0] = new Account (100000); // initial amount of 100k
        System.out.println(acc[0].toString());
        
        acc[0].deposit(50000); //deposit 50k
        System.out.println("Current balance after depositing is: " + "$" + acc[0].getBalance());
        
        acc[0].withdraw(10000);
        System.out.println("Current balance after withdrawing is: " + "$" + acc[0].getBalance());
        
        System.out.println();
        System.out.println("CHECKING ACCOUNT");

        acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
        System.out.println(acc[1].toString());
        
        acc[1].deposit(20000); //I dont know what to do about the chequeDeposit 
        System.out.println("Current balance after depositing is: " + "$" + acc[1].getBalance()); 
        
        System.out.println();
        System.out.println("SAVINGS ACCOUNT");

        acc[2] = new SavingsAccount(10, 50000);
        System.out.println(acc[2].toString());

        acc[2].deposit(10000);
        System.out.println("Current balance after depositing is: " + "$" + acc[2].getBalance()); 
        
        acc[2].addInterest();
    }
}

我仍然是新手,所以很抱歉,如果这是一个不好的问题,但是我尝试与每个班级一起玩,但我仍然不知道如何使用 addiNterest()方法我在 savingsaccount 类中创建了 account 类。我尝试了 savingsaccount.addinterest(),但我会遇到静态参考错误。我以为 acc [2] .addinterest()会起作用,但它说它对类型 account 的类型不确定。

public class Account {
    double currentBalance;
    
    Account(double currentBalance) {
        this.currentBalance = currentBalance; 
    }
    
    double getBalance() {
        return(this.currentBalance);
    }
    
     void deposit(double amount) {
        this.currentBalance += amount;
    }

    void withdraw(double amount) {
        this.currentBalance -= amount;
    }
    
    public String toString() {
        return("Your current account balance is: 
quot; + this.currentBalance);
    }
}
 public class SavingsAccount extends Account {
    double interestRate;

    SavingsAccount(double interestRate, double amount) {
        super(amount);
        this.interestRate = interestRate;
    }

    void addInterest(double interestRate) {
        this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
    }
    
    public String toString() {
        return("Your current account balance is: 
quot; + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
    }
}
public class AccountTester {
    public static void main(String[] args) {
        System.out.println("Welcome to the COMP 251 BANK");
        
        Account[] acc = new Account[10];

        acc[0] = new Account (100000); // initial amount of 100k
        System.out.println(acc[0].toString());
        
        acc[0].deposit(50000); //deposit 50k
        System.out.println("Current balance after depositing is: " + "
quot; + acc[0].getBalance());
        
        acc[0].withdraw(10000);
        System.out.println("Current balance after withdrawing is: " + "
quot; + acc[0].getBalance());
        
        System.out.println();
        System.out.println("CHECKING ACCOUNT");

        acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
        System.out.println(acc[1].toString());
        
        acc[1].deposit(20000); //I dont know what to do about the chequeDeposit 
        System.out.println("Current balance after depositing is: " + "
quot; + acc[1].getBalance()); 
        
        System.out.println();
        System.out.println("SAVINGS ACCOUNT");

        acc[2] = new SavingsAccount(10, 50000);
        System.out.println(acc[2].toString());

        acc[2].deposit(10000);
        System.out.println("Current balance after depositing is: " + "
quot; + acc[2].getBalance()); 
        
        acc[2].addInterest();
    }
}

I'm still new to this so I'm sorry if this is a bad question, but I tried playing around with each class and I still can't figure out how to use the addInterest() method I created in the SavingsAccount class that extends the Account class. I tried SavingsAccount.addInterest() but I get a static reference error. I thought acc[2].addInterest() would work, but it says its undefined for the type Account.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

权谋诡计 2025-02-03 13:14:09

您需要在调用该方法之前将 ACC [2] 施加到 savingsaccount

((SavingsAccount) acc[2]).addInterest();

它被称为降落和这是对它的解释

You need to cast acc[2] to SavingsAccount before calling the method.

((SavingsAccount) acc[2]).addInterest();

It is called downcasting and here is an explanation of it.

始于初秋 2025-02-03 13:14:09

问题

您正在尝试从基类参考调用子类方法的 。 帐户不提供 addintereset()方法。即使在您的情况下,很明显, arr [2] 包含 savingsaccount 实例,Java只能在运行时告诉它。在编译时,您的语法必须符合声明的类型( account )。

想象一下以下场景,其中代码不像您那样简单。 Java在编译时如何告诉数组的每个索引中实际存在哪个实例?只是不能。它将知道,只有在运行时,它才需要检查参考 acc [i] 指向的对象实际上对应于 account SavingsAccount 。

Account[] acc = new Account[10];
for (int i = 0; i < 10; i++) {
    acc[i] = Math.round(Math.random()) == 0 ? new Account(0) : new SavingsAccount(3.5, 0);
}

解决问题的解决方案

,您可以声明您的类型 savingsAccount ,但是那时它只能包含类型 savingsaccount > savings>>(否 account> account account < /code>或其他子类实例,例如 checkingAccount ),或诉诸降低。在您的情况下,您可以使用downcasting并像这样调整代码:

((SavingsAccount) acc[2]).addInterest();

铸造时的最佳实践

,但是,通常在铸造之前,您应始终确保给定的参考实际上指向铸件类型的对象,以避免 ClassCastException 。这可以用运算符 实例或将对象类与所施放的类型进行比较。

// instanceof approach
for (int i = 0; i < 10; i++) {
    if (acc[i] instanceof SavingsAccount) {
        ((SavingsAccount) acc[i]).addInterest(1);
    } else {
        acc[i].deposit(3);
    }
}

// getClass() approach
for (int i = 0; i < 10; i++) {
    if (acc[i].getClass() == SavingsAccount.class) {
        ((SavingsAccount) acc[i]).addInterest(1);
    } else {
        acc[i].deposit(3);
    }
}

The issue

You're trying to invoke a child class' method from a base class reference. Account does not offer the addIntereset() method. Even though in your case it is obvious that arr[2] contains a SavingsAccount instance, Java is able to tell that only at run-time. At compile time, your syntax must be compliant with the declared type (Account).

Imagine a scenario like the following, where the code is not as straightforward as yours. How can Java tell at compile-time which instance is actually present in each index of the array? It just can't. It will know that only at run-time, where it needs to check if the object pointed by the reference acc[i] actually corresponds to an instance of Account or SavingsAccount.

Account[] acc = new Account[10];
for (int i = 0; i < 10; i++) {
    acc[i] = Math.round(Math.random()) == 0 ? new Account(0) : new SavingsAccount(3.5, 0);
}

Solution

To work around your problem, you could either declare your array of type SavingsAccount, but at that point it can only contain objects of type SavingsAccount (no Account or other child class instances like CheckingAccount), or resort to downcasting. In your case, you could use downcasting and tweak your code like this:

((SavingsAccount) acc[2]).addInterest();

Best Practices When Casting

However, in general, before casting, you should always make sure that a given reference actually points to an object of the cast type to avoid a ClassCastException. This can be achieved either with the operator instanceof, or by comparing the object's class with the type you're casting to.

// instanceof approach
for (int i = 0; i < 10; i++) {
    if (acc[i] instanceof SavingsAccount) {
        ((SavingsAccount) acc[i]).addInterest(1);
    } else {
        acc[i].deposit(3);
    }
}

// getClass() approach
for (int i = 0; i < 10; i++) {
    if (acc[i].getClass() == SavingsAccount.class) {
        ((SavingsAccount) acc[i]).addInterest(1);
    } else {
        acc[i].deposit(3);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文