2017-11-25 101 views
0

我有2类(PhoneCall,SMS)扩展另一个(通信)。在不同的类(注册表)中,我有一个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; 
} 

所以程序没有找到在通讯类中的方法,但它是在它的子类之一。 我真的不知道如何继续。如果有人能帮助我,那真是太好了。

回答

2

更改内部检查:

if (i instanceof PhoneCall) { 
    PhoneCall phoneCall = (PhoneCall) i; 
    if (phoneCall.getCallDuration() > longestConvo) { 
     // Do what you need to do.. 
    } 
} 
0

你修改的源应该是这样的:

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类的方法。此外,您必须使用.equals(Object)来比较String类。

相关问题