[java]comment convertir objet

Résolu
domxaline -  
 domxaline -
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)

2 réponses

  1. KX Messages postés 19031 Statut Modérateur 3 020
     
    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
    1. domxaline
       
      ok vs avez raison, j'ai corrigé mon erreur
      merci encore
      0
  2. domxaline
     
    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