09-05-2022
abstraction in java
import java.util.Scanner;
abstract class Animal {
public abstract void eat();
public abstract void sleep();
public abstract void makeSound();
}
class Bird extends Animal {
public void eat() {
System.out.println("Birds love to eat seeds.");
}
public void sleep() {
System.out.println("Sleep for 10-12 hours a day.");
}
public void makeSound() {
System.out.print("Tweet tweet tweet...");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("Cats love to eat salmon.");
}
public void sleep() {
System.out.println("Sleep for 12-14 hours a day.");
}
public void makeSound() {
System.out.print("Meow meow meow...");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("Dogs love to eat vegetables.");
}
public void sleep() {
System.out.println("Sleep for 8-12 hours a day.");
}
public void makeSound() {
System.out.print("Arf arf arf...");
}
}
public class RunAnimal {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Choose an animal. Press B for Bird, C for Cat, or D for Dog:");
char choice = scan.next().charAt(0);
switch(Character.toUpperCase(choice)) {
case 'B':
Bird b = new Bird();
b.eat();
b.sleep();
b.makeSound();
break;
case 'C':
Cat c = new Cat();
c.eat();
c.sleep();
c.makeSound();
break;
case 'D':
Dog d = new Dog();
d.eat();
d.sleep();
d.makeSound();
break;
default:
System.out.print("Invalid input, please restart the program.");
}
}
}