Interfaces

Topic Progress

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Set up a project in Eclipse like usual but make sure you choose new >>interface (not class) for the Animal interface


create a new Java interface for animal and paste thefollowing code

1
2
3
4
public interface Animal {
   public void eat();
   public void travel();
}

Create the other classes by pasting the code below into Amphibian class, Mammal class,and createAnimals class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Amphibian implements Animal {

   public void eat() {
      System.out.println("Amphibian eats");
   }

   public void travel() {
      System.out.println("Amphibian travels");
   }

   public int noOfLegs() {
      return 0;
   }

 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Mammal implements Animal {

    public void eat() {
        System.out.println("Mammal eats");
    }

    public void travel() {
        System.out.println("Mammal travels");
    }

    public int noOfLegs() {
        return 0;
    }

}
1
2
3
4
5
6
7
8
9
10
11
public class CreateAnimals {
      public static void main(String args[]) {
          Mammal m = new Mammal();
          m.eat();
          m.travel();
       
      Amphibian a = new Amphibian();
      //a.eat();
      a.travel();
   }
}

In the Mammal class comment out the method travel. You should find that it doesn’t compile. This is because Mammal implemts the Animal interface so must include methods for eat and travel. Add a new method in the interface makeSound and test by adding it and leaving it out.