gpt4 book ai didi

java - java的继承与多态

转载 作者:行者123 更新时间:2023-12-01 19:18:44 25 4
gpt4 key购买 nike

我有一个基类 Customer 的对象数组。它有 3 个子类 Account1、Account2 和 acount3。当我运行一个循环检查每个帐户的类型然后适本地分配它时,最后我只得到空的数据字段。

这样的事情可以做吗?

                 public static int readFile(String filename, Customer[] review)throws IOException{

Scanner scan = new Scanner (new File (filename));

/*Reading the first record separatly*/
Customer first = new Customer();
Account1 first1= new Account1();
Account2 first2= new Account2();
Account3 first3 = new Account3();

String[] a = scan.nextLine().split("=");
first.set_account_id(Integer.parseInt(a[1].trim()));

a = scan.nextLine().split("=");
first.set_name(a[1].toUpperCase().trim());

a = scan.nextLine().split("=");
first.set_address(a[1].trim());
a= scan.nextLine().split("=");
first.set_accType(a[1].trim());

if (first.get_accType().equals("Saving")){
first = first1;
}

else if(first.get_accType().equals("Checking")){

first = first2;
}

else if(first.get_accType().equals("Fixed")){

first = first3;
a = scan.nextLine().split("=");
first3.set_intRate(Double.parseDouble(a[1].trim()));
}

此代码为我的对象提供了空数据字段..

最佳答案

首先我们必须区分对象和变量。 Customer 类型的变量可以保存对 Customer 类型的任何对象或从 Customer 派生类型的任何对象的引用。赋值将变量设置为引用不同的对象。赋值根本不会改变对象本身。根据这个推理,分配不会导致数据丢失。

现在,您询问是否可以将基类的对象分配给用于保存派生类型的变量,例如子类 obj = new BaseClass()。这是无法完成的,因为基类的对象不是派生类型的对象。反过来也是可能的,例如'BaseClass obj = new SubClass()' 作为派生类型的对象是基类的对象。

但是,如果您有一个保存对基类型的引用的变量,并且将派生类型的对象分配给该变量,则可以使用强制转换将该对象分配给派生类型的变量:

BaseClass obj = new SubClass();
Subclass subObj = (SubClass) obj;

在您的示例中,您执行以下操作:

  1. 您创建一个 Customer 对象并首先分配对变量的引用
  2. 您首先更改变量中引用的 Customer 对象的状态
  3. 首先将变量中的引用替换为对 Account1 对象的引用

这一系列事件不会导致预期的结果,我收集到的是在 Account1 对象中调用了 setName 和 setAdd 方法。实际上,当通过变量first查看时,赋值first=first1将重置情况(对象first和first1的内部状态保持不变)。

您打算做的事情应该按如下方式完成

  private static String nextProperty(Scanner scanner) {
return scanner.nextLine().split("=").trim()
}


public static int readFile(...) {
...
final int accountId = Integer.parseInt(nextProperty(scan));
final String accountName = nextProperty(scan);
final String accountAddress = nextProperty(scan);
final String accountType = nextProperty(scan);

Customer account = null;
if(accountType.equals("Saving")) {
account = new Account1();
} else if (accountType.equals("Checking")) {
account = new Account2();
} else if (accountType.equals("fixed")) {
account = new Account3();
((Account3)account).set_intRate(Double.parseDouble(nextProperty(scan)));
} else {
throw new IllegalStateException("Unexpected account type encountered");
}
account.set_account_id(accountId);
account.set_name(accountName);
account.set_address(accountAddress);
account.set_accType(accountType);
...

}

关于java - java的继承与多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5449548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com