我已經寫了這段代碼。產出應計算銀行的利息,但它給出0.0作爲產出。我創建了一個名爲Bank的類,並將其擴展到ICICI類。Java繼承:爲什麼這個程序給出了0.0輸出
import java.util.Scanner;
public class Bank
{
static double rate;
// n = number of years
public double calculateInterest(double PrincipalAmount, double n)
{
double interest;
interest = (PrincipalAmount * n*rate) /100; // interest formula
return interest;
}
public static void main(String[] args)
{
Scanner s1 = new Scanner(System.in);
System.out.print("Enter PrincipalAmount :");
double PrincipalAmount = s1.nextDouble();
Scanner s2 = new Scanner(System.in);
System.out.print("Enter Number of Years :");
double n = s2.nextDouble();
ICICI ic;
ic = new ICICI();// new object created of ICICI Class
ic.rate = rate; // object call by reference
System.out.print("Interest of ICICI is " + ic.calculateInterest(PrincipalAmount,n));
}
}
public class ICICI extends Bank
{
double rate = 4;
}
即使我們刪除靜態,它仍然會引用Bank類中的rate變量。所以你的邏輯不成立。 –
@ user3689942即使它是非靜態變量,也不能覆蓋它。 –