- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个基类 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;
在您的示例中,您执行以下操作:
这一系列事件不会导致预期的结果,我收集到的是在 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/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!