Hi have one class like this
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;
}
}
And then a Message class
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;
}
}
And one subclass
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);
}
}
On my code I have this:
for (MobilePhone item : listaTelefones) {
for (Message item2: item.getMessages()){
((SMS) item2).showMessage();
}
}
And it gives me this error:
Exception in thread "main" java.lang.ClassCastException: Message cannot be cast to SMS
Can’t I downcast Message to SMS so I can use the SMS showMessage() method?
Some of the items in the list are of class
Messagebut not of classSMS. Therefore, you can not cast them to classSMS.Add something like this to ensure you are dealing with
SMS: