3

I'm self learning Java, and I'm stuck on a chapter about Interfaces. I simply cannot understand how they work in Java.

I believe I understand perfectly what Interface means and how they apply in everyday situations and technology.

But when it comes to Java, code-wise and logic-wise, I'm stuck. I don't get it. How does the concept work?

Say I have 3 objects, and 1 interface object. 2 Objects are ObjectCalculatingA, ObjectCalculatingB, ObjectMathFunctions, and ObjectInterface.

Supposedly in ObjectInterface there must be some sort of reference to the ObjectMathFunctions, so that ObjectCalculatingA and B can just access the math functions in ObjectMathFunctions without writting them all again in A and B.

Am I right?

4
  • Interface is like abstract base class, but not the same. To implement/override base class methods, your class needs to extend base class. That means to implement methods using inheritence you need to follow some strict concept hierarchy. But anybody can implement inteface methods with general hierarchy. Commented Jan 22, 2014 at 11:10
  • interfaces are intended as abstractions of a certain functionality. a contract that dictates and describes what methods, properties and the like a certain class has to have, regardless of what particular class you're talking about. this is useful (for example) when you need classes to decouple from each other, while allowing them to interact. Commented Jan 22, 2014 at 11:10
  • Unless your class that implements interface is abstract all methods in interface needs to be defined in your class. Commented Jan 22, 2014 at 11:13
  • @NoCanDo : Its customary on StackOverflow to leave out the pleasantries and conversational tone. (Eg "explain to me like I'm 5, thanks in advance", etc). . this might sound rude, but it makes it much easier for other people to benefit from your question in future. Commented Jan 22, 2014 at 12:23

4 Answers 4

4

An interface exists to facilitate polymorphism. It allows declaring a contract that any class that implements the interface must honor. And so it is a way to achieve abstraction and model complexity by looking for commonality between things.

An example? How about shapes? All shapes have an area, right? So you could have the following classes:

  • Square
  • Circle

Then let's say you have another class that allows you to collect shapes, and return the total area:

for (Shape shape in shapes) { area += shape.area() //This is polymorphism } 

In the example above, we don't care whether the shape is a square or a circle. We can accept either. We only care that it implements the Shape interface. Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . See now how we're managing complexity? We can use the class without having to worry about all of the things that go on inside. At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details.

This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. The other key foundation concepts in Object Oriented Programming are:

. . . you'll also need to learn these.

Abstract Base Class vs Interface

As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. Which should you choose?

  • Use an interface class implementing it will have its own hierarchy and dependencies. For example a media player. A Movie Player and a Sound Player might have totally different base classes, so use an interface.

  • Use an Abstract base class when you have some commonality between things, but the specifics vary. For example a message parsing framework.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess I was wrong then about Interface. Your last example, the first bullet point, that's actually how I understood Interface. You got 3 Classes, in your example 3 media players, but all 3 share for example the stop-button. Now you've got the Interface with the stop-button in it, that stop-button references to another class where the actual method is. That's how I understood it. I was wrong then.
@NoCanDo It takes time, but it will make sense soon enough. Don't worry if its still not 100% clear yet. . keep trying.
4

In simple lay mans language. Interface is a contract and classes implementing the interface need to adhere to the contract. There can be many implementations for same interface and users can select which implementation they wish to use. For more detailed information I suggest you read book like HeadFirst JAVA.

Once you begin software development you will understand that many a times you would come across an already implemented piece of code which you feel is not properly implemented. But at the same time a colleague of yours feels its correctly implemented and serves his purpose. This is where interfaces come into play. Your colleague who feels this implementation works for him can continue using the current one whereas you can implement your new implementation but you need to make sure that it adheres to the interface so that in future if your implementation is better, your colleague will have an oion to switch over.

List<String> myList = new ArrayList<String>(); 

In above example arraylist is on of the implementations of the List interface. Consider this example, ArrayList is not suiting your requirments so you can do the following.

myList = new LinkedList<String>(); 

This is the power of 'Coding to interface'

Comments

2

From your example, it shows that you lack a basic understanding of Object-Oriented Programming. You are trying to learn how to run without having learned to stand up yet.

In your example, you assume there is a class ObjectMathFunctions. This is not Object-oriented at all, classes should model a real concept.

1. Learn about objects / classes

You should first learn how classes and objects work. A class is not just any arbitrary division of code, it models something real. Examples: Car, Wheel, etc.

2. Learn about inheritance

After you understand that, learn about inheritance: a Car has a getWeight() method. A Wheel has a getWeight() method as well. Hmm, maybe they are both subdivisions of a broader concept: PhysicalThings. Every PhysicalThing has a getWeight() method.

After this, learn about overriding methods in subclasses, learn about abstract classes, etc.

3. Learn about interfaces

Now you will understand that an interface is very similar to an abstract class. You will have done some exercises where you already encountered the problem "This is a PhysicalThing, but it is also CanExplode (e.g. wheel of car, dynamite, etc). This single inheritance model is annoying, how do I fix this?".

1 Comment

Good points, but I think many people actually do well learning in real-time by doing (and then posing questions) - it provides rapid feedback. Progress to the point where you have some questions and then you have a context/foundation upon which to seek more information. . . encapsulation, inheritance, polymorphism. . I wouldn't say its necessary to learn them in that order. . We learn them over and over again anyway.
2

If you know that a class can consist of both data and the functions that operate on the data, then an interface is just a list of the functions that a class has to implement.

Take a light switch interface, ILightSwitch ...

public interface ILightSwitch { void turnOn(); void turnOff(); } 

A class implements an interface if it implements those functions above.

e.g. A LightSwitch class might be

public class LightSwitch implements ILightSwitch { boolean on = false; void turnOn() { on = true; } void turnOff() { on = false; } } 

The LightSwitch class implements the ILightSwitch interface.

1 Comment

Good to go right back to the very basics and describe the features of an interface.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.