[英]how to use a subclass specific method in a different class?
我有2个类(PhoneCall,SMS),它们扩展了另一个类(Communication)。 在不同的类(注册表)中,我有一个ArrayList承载所有传入的通信,包括电话和短信。 我的作业要求我创建一个方法,该方法返回持续时间最长的电话(类PhoneCall的属性)。 因此,当我通过通讯运行ArrayList时,出现一个错误,提示无法解析PhoneCall类中存在的方法getCallDuration()。
public PhoneCall getLongestPhoneCallBetween(String number1, String number2){
double longestConvo=0;
for(Communication i : communicationsRecord){
if(i.getCommunicationInitiator()==number1 && i.getCommunicationReceiver()==number2){
if(i.getCallDuration()>longestConvo){
}
}
}
return null;
}
因此,该程序未在“通信类”中找到该方法,而是在其子类之一中。 我真的不知道该如何进行。 如果有人可以帮助我,那就太好了。
将内部检查更改为:
if (i instanceof PhoneCall) {
PhoneCall phoneCall = (PhoneCall) i;
if (phoneCall.getCallDuration() > longestConvo) {
// Do what you need to do..
}
}
修改后的源应为:
public PhoneCall getLongestPhoneCallBetween(String number1, String number2){
double longestConvo=0;
PhoneCall temp=null;
for(Communication i : communicationsRecord){
if(i instance of PhoneCall){
PhoneCall p=(PhoneCall)i;
if(p.getCommunicationInitiator().equals(number1) && p.getCommunicationReceiver().equals(number2)){
if(p.getCallDuration()>longestConvo){
longestConvo=p.getCallDuration();
temp=p;
}
}
}
}
return temp;
}
在此,将检查该实例仅属于PhoneCall
类,然后将Communication
对象PhoneCall
转换为PhoneCall
以获取特定于PhoneCall
类的方法。 另外,必须使用.equals(Object)
比较String
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.