繁体   English   中英

Java下垂

[英]Java downcasting

大家好,这样一堂课

import java.util.ArrayList;

public class MobilePhone {

    private String number;
    private ArrayList<Message> messages;



    public MobilePhone(String n) {
        this.number = n;
        this.messages = new ArrayList<Message>();
    }

    public String getNumber() {
        return number;
    }

    public void setMessages(Message messages) {
        this.messages.add(messages);
    }

    public ArrayList<Message> getMessages() {
        return messages;
    }

}

然后是消息类

public class Message {

    protected String sender;
    protected String receiver;
    protected String subject;
    protected String bodyText;
    protected int tipo;

    protected Message() {
        this.sender = this.receiver = this.subject =
        this.bodyText = "";
    }

    protected Message(String s, String r, String sbj, String b, int t ) {
        this.sender = s;
        this.receiver = r;
        this.subject = sbj;
        this.bodyText = b;
        this.tipo = t;
    }

    public String getSender() {
        return sender;
    }

    public String getSubject() {
        return subject;
    }

    public String getBodyText() {
        return bodyText;
    }

    public int getTipo() {
        return tipo;
    }


}

还有一个子类

public class SMS extends Message {
    static int maxBodySize = 160;


    public void showMessage(){
        System.out.println("SMS");
        System.out.println("Subject: " + super.subject);
        System.out.println("Text: " + super.bodyText);
    }
}

在我的代码中,我有:

    for (MobilePhone item : listaTelefones) {
         for (Message item2: item.getMessages()){
             ((SMS) item2).showMessage();
         }
    }

它给了我这个错误:

Exception in thread "main" java.lang.ClassCastException: Message cannot be cast to SMS

我不能将消息下传到SMS以便可以使用SMS showMessage()方法吗?

列表中的某些项目属于Message类,而不属于SMS类。 因此,您不能将它们强制转换为SMS类。

添加类似这样的内容以确保您正在处理SMS

if (item2 instanceof SMS) {
    ((SMS) item2).showMessage();
}

在执行转换之前,您需要检查Message是否为SMS类型,因为并非所有Messages都是SMS

if(item2 instanceof SMS) {
    ((SMS) item2).showMessage();
}

这样可以确保您不会尝试将非SMS类型的消息投射为SMS类型。

您必须将Message到列表中。 要么:

测试类型:

if (item2 instanceof SMS) {
    ((SMS) item2).showMessage();
} else {
    // ?
}

如果您知道他们是短信,请在短信中输入您的列表:

private ArrayList<SMS> messages;

public ArrayList<SMS> getMessages() {
    return messages;
}

暂无
暂无

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

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