[英]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.