2017-05-08 133 views
-1

我已經寫了這段代碼。產出應計算銀行的利息,但它給出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; 
} 

回答

0

calculateInterest方法是使用靜態速率變量不是實例率,繼承不會對變量應用,而不會覆蓋變量。所以靜態速率的默認值將爲0.0,因此calculateInterest將給出0.0(因爲它是雙倍的)答案。

+0

即使我們刪除靜態,它仍然會引用Bank類中的rate變量。所以你的邏輯不成立。 –

+0

@ user3689942即使它是非靜態變量,也不能覆蓋它。 –

0

如果意外改變了賦值語句:

ic.rate =率;

相反,它應該是: rate = ic.rate;

謝謝!