In: Computer Science
Java assignment, abstract class, inheritance, and polymorphism.
these are the following following classes:
Animal (abstract)
o Example output: Tom says meow.
Mouse
o Example output: Jerry is chewing on cheese.
Cat
o Example output: Tom is chasing Jerry.
TomAndJerry
Sample run:
Jerry says squeak.
Tom says meow.
Jerry is chewing on cheese.
Tom is chasing Jerry.
//Java code
public abstract class Animal { /** * Has a name property (string)*/ private String name; /** * Has a speech property (string) */ private String speech; /** * a constructor that takes two arguments, * the name and the speech */ public Animal(String name, String speech) { this.name = name; this.speech = speech; } //getters public String getName() { return name; } public String getSpeech() { return speech; } //setters public void setName(String name) { this.name = name; } public void setSpeech(String speech) { this.speech = speech; } /** * It has a method speak() * that prints the name of the animal and the speech. */ public void speak() { System.out.println(name+" says "+speech); } }
//=====================================
/** * Inherits the Animal class */ public class Mouse extends Animal{ /** * a constructor takes a name and also pass * “squeak” as speech to the super class */ public Mouse(String name) { super(name,"squeak"); } /** * a method chew that takes * a string presenting the name of a food. */ public void chew(String food) { System.out.println(getName()+" is chewing on "+food); } }
//========================================
/** * Inherits the Animal */ public class Cat extends Animal { /** * a constructor takes a name and also * pass “meow” to the super class */ public Cat(String name) { super(name,"meow"); } /** * a method chase that takes a Mouse object. * @param mouse */ public void chase(Mouse mouse) { System.out.println(getName()+ " is chasing "+mouse.getName()); } }
//=======================================
public class TomAndJerry { public static void main(String[] args) { /** * a variable of Animal type and assign * it a mouse named “Jerry” */ Animal mouse = new Mouse("Jerry"); /** * a variable of Animal type and assign * it a cat named “Tom” */ Animal cat = new Cat("Tom"); /** * the method makeAnimalSpeak on * the animals you have created */ makeAnimalSpeak(mouse); makeAnimalSpeak(cat); /** * the mouse chew on “cheese” */ ((Mouse)mouse).chew("cheese"); ((Cat)cat).chase((Mouse) mouse); } /** * a static method makeAnimalSpeak * that takes an Animal object and makes it animal speak. */ private static void makeAnimalSpeak(Animal animal) { animal.speak(); } }
//Output
//If you need any help regarding this solution ........... please leave a comment ......... thanks