-2

I am just learning about Java interfaces. I understand that you can name methods in the interface and use them in different ways in different classes. However, I just wrote a simple program that had two different classes, each with a method of the same name, sayHello(), printing different lines of text. I created an object for each class in the main method. I called the method for object 1 and called the method for object 2, and it worked. So I don't see why using an interface is useful. I was able to accomplish using the same method name for different class objects without creating an interface.

vap
  • 151
  • 1
  • 2
  • 9
  • See this post: http://stackoverflow.com/questions/14033992/interfaces-in-java-what-are-they-for?rq=1 and the related questions in the sidebar. – pcnThird Feb 05 '14 at 02:14

2 Answers2

4
  1. This question will likely be closed as being too broad.
  2. Interfaces are not required, not by any mean, as anything that can be done with them can be done without them. The computer machinery doesn't care, and there are many completely competent languages that are just as "Turing-complete" as Java that don't have them, but remember code isn't written for machines...
  3. Nope, code is written to be understandable by man.
  4. And in this regard interfaces allow for the ability to create understandable and yet complex and flexible code.

The details of all this would require that I write a several page tutorial... which is why this question will likely be closed as being too broad.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
1

Interfaces allow you to use a single reference variable or container for different types of objects, without requiring that those objects share the same inheritance structure. That gives you, the programmer, the ability to have lots of flexibility with less coding.

These two threads have some examples that might help:

Why do we need interfaces in Java?

The importance of interfaces in Java

Community
  • 1
  • 1
pjs
  • 18,696
  • 4
  • 27
  • 56