Skip to content

Instantly share code, notes, and snippets.

@vakho10
Last active March 15, 2023 08:48
Show Gist options
  • Save vakho10/2ced6cdb6223d3e7920d933c8a67f71c to your computer and use it in GitHub Desktop.
Save vakho10/2ced6cdb6223d3e7920d933c8a67f71c to your computer and use it in GitHub Desktop.
Abstract classes and example of using polymorphism.
public abstract class Animal {
public abstract void makeSound(); // Force every animals to have sound
}
public class Cat extends DomesticAnimal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Meou (^-^)");
}
}
public class Cow extends DomesticAnimal {
public Cow(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Moo.");
}
}
public class Dog extends DomesticAnimal {
public Dog(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Woof, woof.");
}
}
public abstract class DomesticAnimal extends Animal {
// Domestic animals should have their names
protected String name;
// Name must be assigned in the constructor
public DomesticAnimal(String name) {
this.name = name;
}
// Name should be retrievable from anywhere
public String getName() {
return name;
}
}
public class Lion extends Animal {
@Override
public void makeSound() {
System.out.println("Lion sound!");
}
}
package ge.tsu.lab4;
public class Main {
public static void main(String[] args) {
// Generally all animals
Animal[] animals = {
new Cat("Pupu"),
new Dog("Frufru"),
new Lion(),
new Wolf(),
new Cat("Kiki"),
new Cow("Milky"),
};
for (Animal animal : animals) {
animal.makeSound();
}
// Domestic ones
DomesticAnimal[] domesticAnimals = {
(DomesticAnimal) animals[0],
(DomesticAnimal) animals[1],
(DomesticAnimal) animals[4],
(DomesticAnimal) animals[5],
};
for (DomesticAnimal domesticAnimal : domesticAnimals) {
System.out.println(
String.format("Domestic animal with name: %s and sound...", domesticAnimal.getName())
);
domesticAnimal.makeSound();
}
}
}
public class Wolf extends Animal {
@Override
public void makeSound() {
System.out.println("Wolf sound!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment