如何在不同的 class 中使用 subclass 特定方法?
how to use a subclass specific method in a different class?
我有 2 classes(PhoneCall,SMS)扩展另一个(Communication)。在另一个 class(注册表)中,我有一个 ArrayList,它托管所有传入的通信,包括 phone 呼叫和短信。我的作业要求我创建一个方法,该方法 returns 具有最长持续时间的 phone 呼叫(class PhoneCall 的属性)。因此,当我 运行 通过 ArrayList 进行通信时,我收到一条错误消息,提示无法解析 PhoneCall class.
中存在的方法 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;
}
所以程序没有在通信Class中找到方法,而是在它的子Class中。
我真的不知道如何进行。如果有人能帮帮我,那就太好了。
将内部检查更改为:
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
class,然后将 Communication
对象转换为 PhoneCall
以获取特定于 [ 的方法=11=] class。另外,你必须使用.equals(Object)
来比较String
classes.
我有 2 classes(PhoneCall,SMS)扩展另一个(Communication)。在另一个 class(注册表)中,我有一个 ArrayList,它托管所有传入的通信,包括 phone 呼叫和短信。我的作业要求我创建一个方法,该方法 returns 具有最长持续时间的 phone 呼叫(class PhoneCall 的属性)。因此,当我 运行 通过 ArrayList 进行通信时,我收到一条错误消息,提示无法解析 PhoneCall class.
中存在的方法 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;
}
所以程序没有在通信Class中找到方法,而是在它的子Class中。 我真的不知道如何进行。如果有人能帮帮我,那就太好了。
将内部检查更改为:
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
class,然后将 Communication
对象转换为 PhoneCall
以获取特定于 [ 的方法=11=] class。另外,你必须使用.equals(Object)
来比较String
classes.