0

Today in class we have just seen the first examples of class, object and interfaces; however, the usefulness of the latter is not clear to me. for example, given the following code:

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

It is not clear to me why we should use an interface if we are to implement the same methods in the class. Can't we write them directly into the class?

The example code was taken from w3schools.

Shyvert
  • 27
  • 4
  • 1
    You could be the main developer, you decide what an Animal should at least be able to do, then other developer write some animals by implementing Animal, then they know at least which method they need to write. So you can write other code using Animal as type and don't both you to know if the instance will have or not that method – azro Sep 23 '20 at 17:40
  • 2
    Try to limit your questions to the subject of **specific technical issues.** Stack Overflow is not a substitute for your professor, your textbook or your teaching assistant, any of which you could have (and should have) consulted rather than posting here. Different resources provide different services -- this concept is neither difficult to understand nor controversial. Stack Overflow is not a general discussion forum. Please read the [help file](https://stackoverflow.com/help) to understand how this site operates. – MarsAtomic Sep 23 '20 at 17:49
  • I don't think it's a bad question, necessarily. The problem is that it's already been answered in detail in many, many places (e.g. https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html). I don't think anybody has time to write an answer that will improve on the many that have already been written. – Kevin Boone Sep 23 '20 at 20:37
  • Also, [Why would I want to use Interfaces?](https://stackoverflow.com/questions/240152/why-would-i-want-to-use-interfaces) and [When should one use interfaces?](https://stackoverflow.com/questions/1686174/when-should-one-use-interfaces) and [When should I use an interface in java?](https://stackoverflow.com/questions/2586389/when-should-i-use-an-interface-in-java) and many more. – jaco0646 Sep 23 '20 at 20:44

0 Answers0