Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Animal.java
- ====================
- public class Animal {
- //fields
- protected boolean _isAlive; //indicated if animal alive
- protected String _name; //animal name
- protected String _sound; //the sound that the animal makes
- public Animal (String name, String sound)
- {
- this._isAlive=true;
- this._name=name;
- this._sound=sound;
- }
- public String makeSound()
- {
- if (this._isAlive)
- return this._name + " makes " + this._sound;
- else
- return this._name + " is dead...";
- }
- public void die()
- {
- this._isAlive=false;
- }
- }
- Mouse.java
- ==================
- public class Mouse extends Animal {
- public Mouse(String name, String sound) {
- super(name, sound);
- }
- }
- Cat.java
- ======================
- public class Cat extends Animal{
- public Cat(String name, String sound) {
- super(name, sound);
- }
- public void eatMouse(Mouse mouse)
- {
- if (this._isAlive && mouse._isAlive)
- mouse.die();
- }
- public void drinkMilk(Cow cow)
- {
- if (cow.giveMilk())
- System.out.println("Yamm Yamm!");
- else
- System.out.println("Yak, "+cow._name+" is dead");
- }
- }
- Cow.java
- ====================
- public class Cow extends Animal {
- public Cow(String name, String sound) {
- super(name, sound);
- }
- public boolean giveMilk()
- {
- return this._isAlive;
- }
- }
- Lion.java
- ===================
- public class Lion extends Animal {
- public Lion(String name, String sound) {
- super(name, sound);
- }
- public void eatCow(Cow cow)
- {
- if (this._isAlive && cow._isAlive)
- {
- cow.die();
- }
- }
- }
- Tester.java
- ================
- public class Tester {
- public static void main(String[] args) {
- final String MOUSE_SOUND="SQuitzz";
- final String CAT_SOUND="MEYOUUU";
- final String COW_SOUND="MOOOOOOO";
- final String LION_SOUND="GRRRRRR";
- Mouse m1=new Mouse("Mishka",MOUSE_SOUND);
- Mouse m2=new Mouse("Zeev",MOUSE_SOUND);
- Cat cat1=new Cat("Mitzi",CAT_SOUND);
- Cat cat2=new Cat("Shushi",CAT_SOUND);
- Cow cow1=new Cow("MushMush", COW_SOUND);
- Cow cow2=new Cow("Mumu", COW_SOUND);
- Lion lev = new Lion("LEV",LION_SOUND);
- System.out.println(lev.makeSound());
- System.out.println(cow1.makeSound());
- System.out.println(cat1.makeSound());
- System.out.println(m1.makeSound());
- System.out.println("==================");
- cat1.eatMouse(m1);
- System.out.println(m1.makeSound());
- cat1.drinkMilk(cow1);
- lev.eatCow(cow1);
- cat1.drinkMilk(cow1);
- cat1.drinkMilk(cow2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement