Name: Section: Class Schedule:: Animal ( Animal ( 0 ) Eat Walk (System. .Println (+ +)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Name:

Imperial, Lhester O.
Section: Class Schedule:
2BSIT-2 TH 5:00 - 8:00 PM

Finals Machine Problem 1

A. Read the instructions carefully.

1. Create an Animal class, which is the abstract superclass of all animals.


a) Declare a protected integer attribute called legs, which records the number of legs for
this animal.
b) Define a protected constructor that initializes the legs attribute.
c) Declare an abstract method eat.
d) Declare a concrete method walk that prints out something about how the animals walks
(include the number of legs).

2. Create a Spider class.


a) The Spider class extends the Animal class.
b) Define a default constructor that calls the superclass constructor to specify that all
spiders have eight legs.
c) Implement the eat method.

3. Create a Fish class. Override the Animal methods to specify that fish can't walk and don't
have legs.

4. Create a class (TestAnimals) with a main method to test out your classes.
a) Create an object from the Spider class, test out all methods
b) Create an object from the Fish class, test out all methods

Write your Classes here


public abstract class Animal {

protected int legs;

public Animal() {
legs=0;
}

public abstract void eat();

public void walk(){


System.out.println("walks with " + legs +" legs");
}
}

public class Spider extends Animal{

public Spider() {
legs = 8;
}

public void eat(){


System.out.println("eating");
}

public class Fish extends Animal{

public Fish() {
legs=0;
}

public void eat(){


System.out.println("eating");
}

public void walk(){


System.out.println("Fish can't walk because it has " + legs +"
legs");
}

public class TestAnimals {

public static void main(String[] args) {


Spider s = new Spider();
Fish f = new Fish();

s.eat();
s.walk();

f.eat();
f.walk();
}

}
Paste Screenshot of Sample output:
B. Create a Class Diagram for your classes.
Write your Class diagram here

Animal
#legs : int

+Animal()
+eat() : void
+walk() : void

Spider Fish
+Spider() +Fish()
+eat() : void +eat() : void
+walk() : void

You might also like