[java]comment convertir objet

Résolu/Fermé
domxaline - Modifié par crapoulou le 3/01/2015 à 21:26
 domxaline - 3 janv. 2015 à 21:51
Bonjour,
je ne sais pas comment convertir objet,quelqu'un peut m'aider svp
Merci

public class<bold> Felin </bold>
{
 public void comportement()
 {
  System.out.println("Se comporte comme un félin");
 }
}
public class <bold>Chat </bold>extends Felin
{}
public class <bold>Tigre</bold>  extends Felin
{
 public void comportement()
  {
   System.out.println("Se comporte comme un tigre");
  }
}
public class <bold>TigreSiberia</bold> extends Felin
{
 public void comportement()
  {
   System.out.println("Se comporte comme un tigre de Siberie");
  }
}
public class <bold>ChatPekinois</bold> extends Felin
{}
public class <bold>TigreBengale</bold> extends Felin 
{}
public class <bold>TesterFelins </bold>
{
 public static void main(String[] args) 
 {
 Felin f=new Felin();
 f.comportement();
 
 Chat c=new Chat();
 c.comportement();
 f=c;
 f.comportement();
 
 Tigre t=new Tigre();
 t.comportement();
 f=t;
 f.comportement();
 
 TigreSiberia ts =new TigreSiberia ();
 f=ts;
 f.comportement();
       <underline> t=ts;</underline>
 t.comportement();
 
 ChatPekinois cp= new ChatPekinois();
 cp.comportement();
 f=cp;
 f.comportement();
 <underline>c=cp;</underline>
 cp.comportement();
 
 TigreBengale tb= new TigreBengale();
 f=tb;
 f.comportement();
 <underline>t=tb;</underline>
 t.comportement();
 }
}

j'ai des erreurs suivantes
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Cannot cast from TigreSiberia to Tigre
Type mismatch: cannot convert from ChatPekinois to Chat
Type mismatch: cannot convert from TigreBengale to Tigre

at TesterFelins.main(TesterFelins.java:22)


A voir également:

2 réponses

KX Messages postés 16740 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 26 mai 2024 3 016
3 janv. 2015 à 21:34
Bonjour,

Tu ne peux pas faire tes conversions sur des classes soeurs. Toutes tes classes héritent de Felin, elles ne peuvent donc être converties que en Felin.
Pour avoir par exemple une conversion d'un TigreBengale en Tigre, il faudrait que TigreBengale extends Tigre, ce qui n'est pas le cas.
1
ok vs avez raison, j'ai corrigé mon erreur
merci encore
0
dans mon cours il a résultat comme ça:

se comporter comme un félin

se comporter comme un félin
se comporter comme un félin

se comporter comme un tigre
se comporter comme un tigre

se comporter comme un tigre deSiberie
se comporter comme un tigre deSiberie

se comporter comme un félin
se comporter comme un félin
se comporter comme un félin

se comporter comme un tigre
se comporter comme un tigre
0