簡體   English   中英

如果沒有關鍵字 infront,該方法如何工作?

[英]how does the method work without a keyword infront?

這是示例代碼


public class BankAccount {
    protected double getBalance() {return 1000.0;}
    }
package test;

public class SavingAccount extends BankAccount{
    protected double getBalance() {return 1010.0;}
    protected void printBalance() {
    System.out.println(super.getBalance());
    System.out.println(getBalance());
    System.out.println(this.getBalance());
    }
}

Super.getBalance() 返回父 class 的值,所以是 1000.0 this.getBalace() 返回當前 object 的值,所以是 1010.0 但我不確定 getBalance() 是如何工作的。 不應該和this.getBalance()一樣嗎? 我如何運行它來查看結果? 我正在使用 eclipse。 沒有找到如何在沒有 main 的情況下運行它。 並且不能只創建一個主要的

public void main (String[] args) {
        SavingAccount.printBalance();
    }

因為“無法從 SavingAccount 類型對非靜態方法 printBalance() 進行 static 引用”

printBalance是一個實例方法。 您需要實例化SavingAccount object 才能調用它。 例如

public static void main(String[] args) {
    SavingAccount sa = new SavingAccout();
    sa.printBalance();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM