Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Newbie - Purpose of Interface?

I tried to read what the purpose is in stackoverfow but I couldn't grasp it. Could someone dumb it down for me?

This is what I'm confused about, what is the purpose of creating an interface when you can do something like this:

eg:

//Code with interface
publicinterface AnimalActions{

publi void sound();

}

public class Cat implements AnimalActions{
  public void sound(){
    System.out.println("roarrr!!");
  }
}

public class Dog implements AnimalActions{
  public void sound(){
    System.out.println("woof");
  }
}

Why not just do:

public class Cat{
  public void sound(){
    System.out.println("roarrr!!");
  }
}

public class Dog{
  public void sound(){
    System.out.println("woof");
  }
}

1 Answer

By using interfaces we can avoid code duplications. For instance if you would like to perform the actions every animal can do on both Cat and Dog objects, you need two methods to do this, if you don't use an interface:

public void performDogActions(Dog dog) {
    dog.sound();
}

public void performCatActions(Cat cat) {
    cat.sound();
}

By using the interface it suffices to only have this one method:

public void performAnimalActions(Animal animal) {
    animal.sound();
}

Another advantage is that if you someday create an Horse class which implements Animal, then you can use instances of Horse in the code that uses the interface, without changing the code.

As a note you should name your interface Animal instead of AnimalActions. When a class (Dog) implements an interface (Animal), you can think of it as Dog is an animal. Since Dog is not an AnimalAction, the name AnimalAction is not a good choice.

Hope this helps