嗨,有一堂这样的课
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() 方法吗?