我已经写了这段代码。产出应计算银行的利息,但它给出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即使它是非静态变量,也不能覆盖它。 –