heritage.py

Created by joelkouakou2080

Created on February 10, 2023

2.13 KB


class Animal {
    private String name;
    private String type;
    
    public Animal(String name, String type) {
        this.name = name;
        this.type = type;
    }
    
    public void makeSound() {
        System.out.println("Je fais un son générique d'animal.");
    }
    
    public void printDetails() {
        System.out.println("Nom : " + this.name);
        System.out.println("Type : " + this.type);
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name, "Chien");
    }
    
    @Override
    public void makeSound() {
        System.out.println("J'aboie comme un chien.");
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name, "Chat");
    }
    
    @Override
    public void makeSound() {
        System.out.println("Je miaule comme un chat.");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog("Medor");
        Animal cat = new Cat("Minou");
        
        System.out.println("Détails du chien :");
        dog.printDetails();
        dog.makeSound();
        System.out.println();
        
        System.out.println("Détails du chat :");
        cat.printDetails();
        cat.makeSound();
    }
}


Dans ce programme, nous définissons
une classe de base Animal avec
deux attributs name et type, 
ainsi qu'une méthode makeSound()
qui produit un son générique pour
les animaux.

Nous définissons ensuite deux
classes enfants Dog et Cat qui
héritent de la classe Animal 
en utilisant le mot clé extends
. Chacune de ces classes redéfinit
la méthode makeSound() pour
produire un son spécifique à leur
type d'animal.

Dans la méthode main(), nous
créons deux objets, un Dog 
nommé "Medor" et un Cat nommé
"Minou". Nous appelons les méthodes
printDetails() et makeSound()
pour chaque objet, et le polymorphisme
s'occupe de faire appel à la 
méthode correcte en fonction
du type sous-jacent de l'objet.

La sortie de ce programme sera
la suivante :
  
  Détails du chien :
  Nom : Medor
  Type : Chien
  J'aboie comme un chien.

  Détails du chat :
  Nom : Minou
  Type : Chat
  Je miaule comme un chat.

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.