2017-05-08 81 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;

谢谢!