简体   繁体   English

如何在不同的类中使用特定于子类的方法?

[英]how to use a subclass specific method in a different class?

I have 2 classes ( PhoneCall ,SMS ) that extend another ( Communication ). 我有2个类(PhoneCall,SMS),它们扩展了另一个类(Communication)。 In a different class (Registry) I have an ArrayList that hosts all incoming communications both phone calls and sms. 在不同的类(注册表)中,我有一个ArrayList承载所有传入的通信,包括电话和短信。 My assignment asks me to create a method that returns the phone call with the longest duration (attribute of class PhoneCall). 我的作业要求我创建一个方法,该方法返回持续时间最长的电话(类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. 因此,当我通过通讯运行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;
}

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. 在此,将检查该实例仅属于PhoneCall类,然后将Communication对象PhoneCall转换为PhoneCall以获取特定于PhoneCall类的方法。 Also, you must use .equals(Object) to compare String classes. 另外,必须使用.equals(Object)比较String类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM