Domanda

Ciao, ho una lezione come questa

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

}

E poi una classe di messaggi

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


}

E una sottoclasse

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

Sul mio codice ho questo:

    for (MobilePhone item : listaTelefones) {
         for (Message item2: item.getMessages()){
             ((SMS) item2).showMessage();
         }
    }

E mi dà questo errore:

Exception in thread "main" java.lang.ClassCastException: Message cannot be cast to SMS

Non riesco a abbassare il messaggio su SMS in modo da poter usare il metodo SMS showMessage ()?

È stato utile?

Soluzione

Alcuni degli elementi nell'elenco sono di classe Message Ma non di classe SMS. Pertanto, non puoi gettarli in classe SMS.

Aggiungi qualcosa del genere per assicurarti di avere a che fare SMS:

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

Altri suggerimenti

Devi verificare se il Message è di tipo SMS Prima di fare il cast come non tutti Messages sono SMS'S.

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

Questo ti assicurerà di non provare a lanciare messaggi che non sono di SMS digitare a a SMS genere.

Devi mettere un Message nella tua lista. O:

Test per il tipo:

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

Se sai che sono SMS, digita la tua lista su SMS:

private ArrayList<SMS> messages;

public ArrayList<SMS> getMessages() {
    return messages;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top