1

嗨,有一堂这样的课

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;
    }

}

然后是 Message 类

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() 方法吗?

4

3 回答 3

2

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

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

if (item2 instanceof SMS) {
    ((SMS) item2).showMessage();
}
于 2012-01-23T12:08:46.703 回答
2

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

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

这将确保您不会尝试将非SMS类型的消息转换为SMS类型。

于 2012-01-23T12:10:05.050 回答
1

你必须Message在你的列表中加入一个。任何一个:

测试类型:

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

如果您知道它们是 SMS,请在 SMS 中键入您的列表:

private ArrayList<SMS> messages;

public ArrayList<SMS> getMessages() {
    return messages;
}
于 2012-01-23T12:11:36.160 回答