I have 2 classes ( PhoneCall ,SMS ) that extend another ( Communication ). In a different class (Registry) I have an ArrayList that hosts all incoming communications both phone calls and sms. My assignment asks me to create a method that returns the phone call with the longest duration (attribute of class PhoneCall). So when I run through the ArrayList with the communications I get an error that says cannot resolve method getCallDuration() that exists in the PhoneCall class.
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;
}
So the program does not find the method in the Communication Class, but it is in one of its sub-Classes. I do not really know how to proceed. If anyone could help me out , it would be really nice.
Change the inner check to:
if (i instanceof PhoneCall) {
PhoneCall phoneCall = (PhoneCall) i;
if (phoneCall.getCallDuration() > longestConvo) {
// Do what you need to do..
}
}
Your modified source should be like:
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;
}
Where, it is checked that the instance is of PhoneCall
class only and the Communication
object is then casted to PhoneCall
to get the methods specific to PhoneCall
class. Also, you must use .equals(Object)
to compare String
classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.