Reputation: 7243
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?
Upvotes: 1
Views: 428
Reputation: 26132
Some of the items in the list are of class Message
but not of class SMS
. Therefore, you can not cast them to class SMS
.
Add something like this to ensure you are dealing with SMS
:
if (item2 instanceof SMS) {
((SMS) item2).showMessage();
}
Upvotes: 2
Reputation: 425073
You must be putting a Message
in your list. Either:
if (item2 instanceof SMS) {
((SMS) item2).showMessage();
} else {
// ?
}
private ArrayList<SMS> messages;
public ArrayList<SMS> getMessages() {
return messages;
}
Upvotes: 1
Reputation: 2281
You need to check if the Message
is of type SMS
before you do the cast as not all Messages
are SMS
's.
if(item2 instanceof SMS) {
((SMS) item2).showMessage();
}
This will make sure you don't try and cast messages which are not of SMS
type to a SMS
type.
Upvotes: 2