使用super.displayInfo调用父类方法时账号等信息显示默认值问题
问题分析与解决
问题原因
你在main方法中创建的Account ac实例和后续的Savings/FixedDeposit实例是完全独立的对象,彼此没有任何关联。子类对象的父类字段(账号、客户名、账户类型、支行名称等)从未被赋值,所以打印时会显示Java的默认值(int类型默认0,String类型默认null)。
解决思路
不需要单独创建独立的Account对象,直接让子类对象初始化父类的属性即可。更规范的做法是给父类添加构造方法,子类通过构造方法调用父类构造,一次性完成所有属性的初始化。
修正后的完整代码
import java.util.*; class Account { int Acno; String CustName, type, Branch; // 父类构造方法,初始化基础账户信息 Account(int n, String nm, String ty, String br) { Acno = n; CustName = nm; type = ty; Branch = br; } void displayInfo() { System.out.println("Account No: " + Acno + "\nCustomer Name: " + CustName + "\nAccount Type: " + type + "\nBranch: " + Branch); } } class Savings extends Account { int Year; double Amount, Rate = 3.5, Interest; // 子类构造方法,先调用父类构造初始化基础信息,再初始化子类字段 Savings(int n, String nm, String ty, String br, int y, double am) { super(n, nm, ty, br); Year = y; Amount = am; } void calIntAmt() { Interest = (Amount * Rate * Year) / 100; } void displayInfo() { super.displayInfo(); System.out.println("Interest: " + Interest); } } class FixedDeposit extends Account { int Year; double Amount, Rate, Interest; // 子类构造方法,初始化所有属性 FixedDeposit(int n, String nm, String ty, String br, int y, double am) { super(n, nm, ty, br); Year = y; Amount = am; } void calIntAmt() { if (Year <= 2) { Rate = 6.5; Interest = (Amount * Rate * Year) / 100; } else if (Year > 2 && Year <= 5) { Rate = 7.5; Interest = (Amount * Rate * Year) / 100; } else if (Year > 5 && Year <= 10) { Rate = 8.5; Interest = (Amount * Rate * Year) / 100; } else if (Year >= 10) { Rate = 9.0; Interest = (Amount * Rate * Year) / 100; } else { System.out.println("Invalid Year"); } } void displayInfo() { super.displayInfo(); System.out.println("Interest: " + Interest); } } public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Account Number: "); int n = sc.nextInt(); System.out.print("Customer Name: "); String nm = sc.next(); System.out.print("Account Type: "); String t = sc.next(); System.out.print("Branch Name: "); String br = sc.next(); System.out.print("Amount: "); int a = sc.nextInt(); System.out.print("Year: "); int y = sc.nextInt(); if (t.equalsIgnoreCase("Saving")) { Savings s = new Savings(n, nm, t, br, y, a); s.calIntAmt(); s.displayInfo(); } else if (t.equalsIgnoreCase("FixedDeposit")) { FixedDeposit fd = new FixedDeposit(n, nm, t, br, y, a); fd.calIntAmt(); fd.displayInfo(); } else { System.out.println("Invalid Account Type"); } sc.close(); } }
额外修正点
- 修复了
FixedDeposit类中displayInfo方法只打印"Interest"无具体值的问题 - 调整了
FixedDeposit利息计算的条件,避免重复判断Year=2的情况 - 修正了输入提示中的拼写错误
Btanch→Branch - 使用
equalsIgnoreCase判断账户类型,避免大小写敏感导致的匹配失败
内容的提问来源于stack exchange,提问作者Dharmik
相关产品推荐
相关产品推荐

